Why can the test sizeof(int) - 1 > 0 behave unexpectedly when the subtraction reaches zero?
Correct answer
A. sizeof yields size_t, so the subtraction is unsigned and wraps to a huge value
18 views
A. sizeof yields size_t, so the subtraction is unsigned and wraps to a huge value
18 views
sizeof produces a value of type size_t, an unsigned type, so in sizeof(int) - 1 the int 1 is converted to size_t and a zero result would wrap to SIZE_MAX rather than becoming negative. The idiom is safe only when the subexpression cannot reach zero; otherwise cast to ptrdiff_t or rewrite the comparison. The same conversion rule makes -1 > 0u evaluate as true.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is A? Ask here and get an explanation.