1. Home
  2. Computer Science MCQs
  3. C Programming
  4. For int n = -1; size_t sz = 4; what is the value of (n <…

Added 30 Nov -0001

For int n = -1; size_t sz = 4; what is the value of (n < sz) in C, and why?

  1. True, because size_t is promoted to int before the comparison under the usual arithmetic conversions in C here
  2. A compile-time error, since signed and unsigned operands may never be compared without an explicit cast
  3. False, because n is converted to size_t in the usual arithmetic conversions and becomes a very large value Correct answer
  4. True, because -1 is promoted to int and then compared as an ordinary signed value in this expression

Correct answer

C. False, because n is converted to size_t in the usual arithmetic conversions and becomes a very large value

15 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs