1. Home
  2. Computer Science MCQs
  3. C Programming
  4. Why can the test sizeof(int) - 1 > 0 behave unexpectedly…

Added 30 Nov -0001

Why can the test sizeof(int) - 1 > 0 behave unexpectedly when the subtraction reaches zero?

  1. sizeof yields size_t, so the subtraction is unsigned and wraps to a huge value Correct answer
  2. The expression is evaluated at run time, so the compiler cannot fold it at all
  3. int is signed, so the subtraction borrows and produces a negative value
  4. The comparison is always true because sizeof(int) alone exceeds zero here

Correct answer

A. sizeof yields size_t, so the subtraction is unsigned and wraps to a huge value

18 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is A? 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