ProgrammingEasyWipro · Capgemini pattern
What is printed?
What is printed?
int next_id(void) {
static int id = 0;
return ++id;
}
int main(void) {
int a = next_id(), b = next_id(), c = next_id();
printf("%d %d %d", a, b, c);
}- A. 1 1 1
- B. 0 1 2
- C. 1 2 3
- D. 3 3 3
Correct answer: C. 1 2 3
A static local variable is initialised once and keeps its value between calls, so the counter goes 1, 2, 3. Without static, id would be re-created as 0 on every call and each call would return 1.
More C Programming questions
- What is printed? c int x = 2; switch (x) { case 1: printf("1"); case 2: printf("2"); case 3: printf("3"); break; default: printf("D"); }
- What is printed? c if (-1 < 1u) printf("yes"); else printf("no");
- What is printed? c int a = 0, b = 0; int x = (++a > 5) && (++b > 0); int y = (++a > 0) || (++b > 0); printf("%d %d %d %d", a, b, x, y);
- What is printed? c printf("%c %d %d", 'A' + 2, 'A' + 2, 'z' - 'a');
- What is printed? c unsigned char a = 250, b = 10, z = 0; int s = a + b; unsigned char t = a + b; z--; printf("%d %d %d", t, z, s);
- What is printed? c int x = 6; printf("%d %d", x & 2 == 2, (x & 2) == 2);