main()
{
int x=12;
unsigned int y=12;
if (x>y)
{
printf("abc");
}
else
{
printf("xyz");
}
}
What is the output ?
After fixing the compiler errors, the signed int
is converted to unsigned, due to the rules on Usual arithmetic conversions (C99 §6.3.1.8):
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
It behaves as expected here, because 12 is within the range of unsigned int
.
However, if you use x = -2;
as suggested in your comment, it will be converted to -2 + UINT_MAX
(per §6.3.1.3, Signed and unsigned integers).
-2 + UINT_MAX > 12
is true, so abc
will print.
That code does not compile. For what it's worth, my compiler gives the following output:
foo.cpp: In function ‘int main()’:
foo.cpp:1: error: ‘printf’ was not declared in this scope
foo.cpp:1: error: ‘printf’ was not declared in this scope
foo.cpp:1: error: expected ‘}’ at end of input
After fixing the errors, the program outputs xyz
, which is expected because signed 12
is not greater than unsigned 12
.
Note: This answer is C99 specific.
Return type of main
is missing (should be int), so your code should not compile.
Furthermore
int main()
{
int x=12;
unsigned int y=12;
if (x>y)
{
printf("abc");
}
else
{
printf("xyz");
}
}
invokes UB because <stdio.h>
is missing
J.2 Undefined behavior
— For call to a function without a function prototype in scope where the function is defined with a function prototype, either the prototype ends with an ellipsis or the types of the arguments after promotion are not compatible with the types of the parameters (6.5.2.2).
Assuming you have included library files, return type of main is not necessary unless you set compiler to strict behavior. so making another assumption that you have not set compiler to behave strictly!, end result would be
xyz
as @Matthew Flaschen said, after conversion, both will be same so first condition wont met and it would go in else part.
You should get a compiler warning saying signed/unsigned mismatch, but it may get optimized away if the compiler determines the values are constant.
精彩评论