1. Home
  2. Computer Science MCQs
  3. C Programming
  4. Why does void *p; p = p + 1; fail to compile as strictly…

Added 30 Nov -0001

Why does void *p; p = p + 1; fail to compile as strictly conforming C?

  1. Because the increment operator is not defined for any pointer type in the language
  2. Because a cast to char * is needed before assigning any value to a void pointer
  3. Because pointer arithmetic needs a complete object type to know the element size Correct answer
  4. Because void pointers may only be compared and never assigned a fresh address

Correct answer

C. Because pointer arithmetic needs a complete object type to know the element size

16 views

MCQSEXAM

Explanation

Pointer arithmetic scales by the size of the pointed-to type, and void is an incomplete type with no size, so adding 1 is ill-formed in C. GCC accepts it as an extension by treating sizeof(void) as 1, which is why the code compiles widely. Portable code casts to unsigned char * first, since that type is guaranteed to have size 1.

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