0

Please explain the code below

#include <stdio.h> void say_hello(); int main() { int i; for (i = 0; i < 5; i++) { say_hello(); } return 0; } void say_hello() { static int num_calls = 1; printf("Hello number %d\n", num_calls); num_calls++; }

30th Jan 2020, 3:18 PM
Harshit Nema
Harshit Nema - avatar
6 Respuestas
+ 2
Notice that the say_hello() function defines num_calls as static. That means num_calls will continue to exist after the function exits. So num_calls will keep its value for the next time when the function gets called, and it keeps incrementing after its one-time initialialization to 1.
30th Jan 2020, 5:28 PM
Brian
Brian - avatar
+ 2
SpîrîT that is correct, say_hello() is called 5 times from the for() loop, as i counts up from 0 to 4. When i becomes 5 the loop exits without calling say_hello() again.
30th Jan 2020, 5:35 PM
Brian
Brian - avatar
+ 2
blackwinter and Brian thank you very much to both.
30th Jan 2020, 5:37 PM
Harshit Nema
Harshit Nema - avatar
+ 1
blackwinter would you explain me about static further more...
31st Jan 2020, 3:20 AM
Harshit Nema
Harshit Nema - avatar
0
blackwinter but the variable is static then how it can change every time?
30th Jan 2020, 5:24 PM
Harshit Nema
Harshit Nema - avatar
0
Brian does it mean the for loop is running the say_hello function to print hello number?
30th Jan 2020, 5:30 PM
Harshit Nema
Harshit Nema - avatar