I tried print the value of static variable 5 times by declaring it in a function where its increments itself for each call and then adding it to global variable and return its value in a printf statement but the output was different than usual all value of the static variable incremented first and output was in the reverse order after adding to the global variable(All the value was printed using a single printf statement)
#include <stdio.h>
int global_variable = 10;
int fun(){
static int var;
printf("The value of var is %d\n", var);
var++;
return global_variable + var;
}
int main()
{
//This works fine
printf("%d\n", fun());
printf("%d\n", fun());
printf("%d\n", fun());
printf("%d\n", fun());
printf("%d\n", fun());
//This works weird this prints value in reverse order not like the former case
printf("\n%d\n%d\n%d\n%d\n%d\n",fun(), fun(), fun(), fun(), fun());
return 0;
}
output of first one:
The value of var is 0
11
The value of var is 1
12
The value of var is 2
13
The value of var is 3
14
The value of var is 4
15
output of second one:
The value of var is 5
The value of var is 6
The value of var is 7
The value of var is 8
The value of var is 9
20
19
18
17
16
In two set of code first one works fine but the second is what i don't understand. Please explain.