noufal
noufal

Reputation: 970

Error while using static variable

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

Answers (4)

anonymous
anonymous

Reputation: 151

The below will work:

#include <stdio.h>

int foo()
{
    static int a = 0;
    a++;
    return a;
}

Upvotes: 0

dead programmer
dead programmer

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

Sadique
Sadique

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

dragosht
dragosht

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

Related Questions