ProgrammingVery hardProduct company OA · GATE CS

Does this function compile, and what does it do?

Does this function compile, and what does it do?
struct S { int *p; };
void f(const struct S *s) { *s->p = 5; }
  1. A. It fails to compile because s points to a const struct
  2. B. It fails to compile because -> cannot be used on a const pointer
  3. C. It compiles but writing through s->p is undefined behaviour in every case
  4. D. It compiles: const makes the member pointer itself read-only, not the int it points to, so the write is allowed

Correct answer: D. It compiles: const makes the member pointer itself read-only, not the int it points to, so the write is allowed

Through a const struct S *, the member p has type int *const: you cannot change where p points, but *p is a plain int. const is shallow; it does not reach through pointers stored in the struct.

More C Programming questions

Exams that ask this topic