Reputation: 970
I am learning C. Why doesn't the static variable increase above1
.
#include <stdio.h>
int foo()
{
static int a = 0;
return a+1;
}
int main()
{
int i;
for (i = 0; i < 10; i = foo())
printf("%d\n", i);
return 0;
}
Where is the mistake in this code ?
Upvotes: 2
Views: 113
Reputation: 151
The below will work:
#include <stdio.h>
int foo()
{
static int a = 0;
a++;
return a;
}
Upvotes: 0
Reputation: 4373
This is a infinite loop as you are returning a+1. every time it will return 0+1 and your a's value is not getting updating. as per you condition in you loop the loop runs infinity until the timeout occur. try this here a's value is keep on updating in every function call.
int foo()
{
static int a = 0;
a++;
return a;
}
Upvotes: 0
Reputation: 22841
Because you are not storing anything back into it. This should work for you:
int foo()
{
static int a = 0;
return ++a;
}
Here return ++a
means a = a + 1
, i.e., increment a first then return its value. a+1
evaluates to 1
but does not store anything back into a
Upvotes: 5
Reputation: 3275
You are never assigning a value to the "a" variable. You are just returning the value of a+1 from your routine.
Upvotes: 0