Subscribes to unsigned conversions

Possible duplicate:
Riddle (C)

see this code

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) int array[] = {23,34,12,17,204,99,16}; int main() { int d; for(d=-1;d <= TOTAL_ELEMENTS-2;d++) printf("%d\n",array[d+1]); return 0; } 

Now this loop will not start. sizeof () will return an unsigned value, so TOTAL_ELEMENTS has an unsigned value. Now, having come to the for loop, please tell me whether the unary operator "-" works on signed int 2 or the implicit conversion to unsigned, and then the "-" operator works.

+4
source share
5 answers

In your example, d is converted to unsigned int in comparison. But -1 cannot be represented as an unsigned int value, so it is converted to UINT_ MAX. To avoid this behavior, you can convert the right side of the comparison to a signed int by adding (int).

See Understanding Integer Conversion Rules for details on converting an integer to C.

+8
source

There is no unary operator in d <= TOTAL_ELEMENTS-2.

TOTAL_ELEMENTS-2 comes down to an expression with a binary operator -. This expression then becomes unsigned because one of its operands is unsigned.

In the case of d <= TOTAL_ELEMENTS-2, type d is also converted to unsigned int for the same reason.

The relevant part of the standard is section 6.3.1.8 No. 1 (ISO / IEC 9899: 1999), which states:

"Otherwise, if the operand with an unsigned integer type has a rank greater than or equal to the ranks of the type of another operand, then the operand with an integer type with a sign is converted to the type of the unsigned operand of an integer type.

+2
source

Yes, d also has an unsigned type in this expression due to career advancement, so the loop breaks down.

However, the question is, the C compiler "thinks":

(unsigned) ((unsigned) 5 - (unsigned) 2)

i.e. promotion 2 to unsigned or:

(unsigned) ((unsigned) 5 - (signed) 2)

i.e. subtraction using operands of both types. Of course, this does not matter, since it will be the same operation for both. However, the whole point is that subtraction returns a value of one type, so theoretically it can only accept arguments of this type. So this is the first (unsigned int 2).

PS (-2) is unary, and (5 - 2) binary.

+2
source

I suspect that the unsigned type sizeof() extends to the expression TOTAL_ELEMENTS-2 , and then to both operands d <= TOTAL_ELEMENTS-2 . Inserting (int) juste before TOTAL_ELEMENTS fixes the problem.

0
source

See that the "-" operator, which is unary, was a stupid thing. Forget about it. It was a binary "-", I understand.

when 2 is converted to unsigned int, it becomes unsigned 2, so TOTAL_ELEMENTS-2 has a value equal to unsigned 5, and then when d is converted to unsigned int, it gets a large positive value and therefore the loop fails.

what is going on here?

and yes, I did not write this code, it is some kind of puzzle that I found on the Internet. Thank you all.

0
source

All Articles