22.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
(C/C++) Find the output of the following code.**
#include <stdio.h>
int main(){
int x = 5;
int * const ptr = &x;
++(*ptr);
printf("%d", x);
return 0;
}
Pick ONE option
Show answer & explanation
Answer: A. 6
The declaration int * const ptr = &x; creates a const pointer to int (the pointer itself is constant, not the data it points to). The expression ++(*ptr) dereferences the pointer and increments the value at that address (x) from 5 to 6. Therefore, printf("%d", x) outputs 6.
Step-by-step Derivation:
int x = 5;— x is initialized to 5.int * const ptr = &x;— ptr is a const pointer pointing to x. The const qualifier means ptr cannot be changed to point elsewhere, but the data it points to (x) can be modified.++(*ptr);— Dereference ptr to get x, then increment it: x becomes 6.printf("%d", x);— Print the value of x, which is now 6.
Output: 6