For int n = -1; size_t sz = 4; what is the value of (n < sz) in C, and why?
Correct answer
C. False, because n is converted to size_t in the usual arithmetic conversions and becomes a very large value
15 views
C. False, because n is converted to size_t in the usual arithmetic conversions and becomes a very large value
15 views
Usual arithmetic conversions promote the signed operand to the unsigned type whenever the unsigned type has at least the rank of int, so -1 becomes SIZE_MAX and the comparison is false. This mechanism underlies bugs where an unsigned loop counter never reaches a negative termination value. Cast to a wide signed type when a negative sentinel is possible.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is C? Ask here and get an explanation.