2

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 ?

2
  • Why do you think it would? Commented Oct 8, 2013 at 13:10
  • @ColeJohnson then I didn't know that it doesn't make any sense. Now I got it. Commented Oct 8, 2013 at 13:18

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

0

You are never assigning a value to the "a" variable. You are just returning the value of a+1 from your routine.

Comments

0

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;
}

Comments

0

The below will work:

#include <stdio.h>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.