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; }- A. It fails to compile because s points to a const struct
- B. It fails to compile because -> cannot be used on a const pointer
- C. It compiles but writing through s->p is undefined behaviour in every case
- 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
- On a two's-complement machine, what is printed? c int x = 5; printf("%d %d", -~x, ~-x);
- What is printed? c const char s = "ab cd"; printf("%zu", strlen(s));
- On an LP64 system (32-bit int, 64-bit long), what is printed? c printf("%zu %zu", sizeof(2147483647), sizeof(2147483648));
- What is printed? c printf("%d %d", '0', '0');
- What is printed? c printf("%d %d", !!"", !"");
- How many subsets does this code count? c int a[] = {2, 3, 5, 7, 8}, c = 0; for (int m = 0; m < 32; m++) { int s = 0; for (int i = 0; i <…