What will be the output of the following C code? #include<stdio.h> int main()…
2024
What will be the output of the following C code?
#include<stdio.h>
int main()
{
int a = 1;
a += 3;
printf("%d", a + a);
return 0;
}- A.
4
- B.
6
- C.
8
- D.
10
- E.
2
Attempted by 211 students.
Show answer & explanation
Correct answer: C
Concept
The compound-assignment operator x += k is exactly equivalent to x = x + k: it reads the current value of the variable, adds k, and writes the result back. After that statement the variable holds the updated value, and any later expression sees only that updated value.
Applying it to this code
int a = 1; initialises a with the value 1.
a += 3; means a = a + 3 = 1 + 3, so a now holds 4.
printf("%d", a + a); evaluates a + a with the current value of a, that is 4 + 4 = 8, and prints it.
Cross-check
Substituting the final value back: a is 4, so a + a is 4 + 4 = 8. The single conversion specifier %d consumes the one integer argument a + a, so exactly 8 is written to the output.
Loading lesson…