1. Home
  2. Computer Science MCQs
  3. C Programming
  4. In C (not C++), what is the status of storing a value in…

Added 30 Nov -0001

In C (not C++), what is the status of storing a value in one union member and then reading a different member of the same size?

  1. Undefined behaviour in C as well, exactly as it is in C++, so the compiler may assume it never happens
  2. A constraint violation, so a conforming compiler must reject the program instead of silently reinterpreting it
  3. Permitted; the bytes are reinterpreted and the result is implementation-defined, which is called type punning Correct answer
  4. A conversion that applies the usual arithmetic conversions to the stored bytes before reading them back

Correct answer

C. Permitted; the bytes are reinterpreted and the result is implementation-defined, which is called type punning

16 views

MCQSEXAM

Explanation

Type punning through a union is allowed in C, where the result depends on the object representation and hence on endianness and padding, while C++ restricts it to the common initial sequence of standard-layout structs. A union holding a float and a uint32_t is thus a legal C reinterpretation but formally undefined in C++. memcpy is the portable alternative in both languages.

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