ProgrammingVery hardProduct company OA

Which of the numbered statements violate a constraint (i.e. must be rejected by the compiler)?

Which of the numbered statements violate a constraint (i.e. must be rejected by the compiler)?
typedef char *str_t;
#define STR_M char *
char buf[] = "abc", alt[] = "xyz";
const str_t p = buf;
const STR_M q = buf;
/* 1 */ p[0] = 'A';
/* 2 */ p = alt;
/* 3 */ q[0] = 'B';
/* 4 */ q = alt;
  1. A. 1 and 3 only
  2. B. 2 and 4 only
  3. C. 1, 2, 3 and 4
  4. D. 2 and 3 only

Correct answer: D. 2 and 3 only

A typedef is a real type name, so const str_t makes the POINTER itself const: char *const p. Writing through it (1) is fine, re-seating it (2) is an error. The macro is plain text: const STR_M q becomes const char *q, a modifiable pointer to const chars, so (3) is an error and (4) is fine. '1 and 3' reads both declarations as const char *, which is exactly the trap of mixing typedef and #define.

More C Programming questions

Exams that ask this topic