ProgrammingModerateAccenture · Capgemini pattern
What is printed?
What is printed?
int tick(int reset) {
static int c = 10;
if (reset) c = 0;
return c += 2;
}
int main(void) {
int a = tick(0);
int b = tick(1);
int c = tick(0);
printf("%d %d %d", a, b, c);
}- A. 12 2 4
- B. 12 12 14
- C. 2 2 4
- D. 12 2 2
Correct answer: A. 12 2 4
A static local is initialised once, before the first call, and keeps its value between calls; the initialiser does not run again. Call 1: 10 + 2 = 12. Call 2 resets to 0, then 2. Call 3 continues from 2 to 4. The main's local c is a different variable.
More C Programming questions
- What is printed? c int i, j; for (i = 0, j = 0; i < 5; i++, j += i); printf("%d %d", i, j);
- What is printed? c / LP64: 4-byte int, 8-byte long, 4-byte float / char c = 'a'; short s = 2; printf("%zu %zu %zu %zu", sizeof(c)…
- What is printed? c / x86-64 LP64: natural alignment (double 8, int 4, short 2) / struct X { char a[5]; double d; char e; }; struct Y {…
- What is printed? c void p(const char s) { if (!s) return; putchar(s); p(s + 2); putchar(s); } int main(void) { p("abcdef"); }
- What is printed? c / LP64: 4-byte int, 8-byte pointers / int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; int (p)[3] = a; printf("%d %d %zu %zu"…
- What is printed? c int i, c = 0; for (i = 0; i < 6; i++) if (i % 2 == 0 || ++c > 1) c += 10; printf("%d %d", i, c);