+ 1

What do these code snippets print? Can you explain its behaviour?

#include <stdio.h> void proc(void); int main(){ printf("First start:\n"); proc(); printf("Second start:\n"); proc(); printf("Third start:\n"); proc(); return 0; } void proc(void){ static int a; printf("Variable a = %d\n", a); a++; }

3rd Jun 2019, 7:38 AM
Caveman
Caveman - avatar
2 Answers
+ 8
You could run this code in Code Playground.
3rd Jun 2019, 7:49 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 8
First start: Variable a = 0 Second start: Variable a = 1 Third start: Variable a = 2 static variables only need to be declared once and when declared multiple times, they just refer back to the original one. So initially you created a with a default value of 0. Then you post incremented 3 times. Therefore, your output is 0, followed by a plus one to 1, followed by a plus one to 2, followed by a plus one.
3rd Jun 2019, 7:52 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar