0

I've defined a function like this

static void
flatten_tree(...)
{
  static int num = 0;
  ...
}

However, when the function is executed, num gets some random value, rather than 0 on the first run. Upon subsequent function calls it behaves as static var should do. Aren't static variables explicitly initialized with zero? What is the proper way to initialize it?

11
  • 5
    how do you know it's not initialized to 0? can you show us? Commented Dec 17, 2013 at 15:22
  • 2
    Show more code. It's possible a pointer on the stack is overwriting the values. Commented Dec 17, 2013 at 15:27
  • 1
    compiler supposed to initialize all static to 0. Is it always a different random value ? Commented Dec 17, 2013 at 15:27
  • 6
    I am guessing you are looking that in your GDB when the control is on that line, when it's not initialized yet. But actual initialization happens only after you type next ;-) Commented Dec 17, 2013 at 15:28
  • 1
    According to the documentation all static variables has initial default value zero. if you think you're right show us the code. Commented Dec 17, 2013 at 15:29

1 Answer 1

0

If it's not set to zero the first time it's called then either your C implementation is broken, your debugger is broken, or you've made some other error - I won't comment on which is the most likely scenario :-)

If you really want to see what it's doing, chage your code temporarily to something like:

static void
flatten_tree(...)
{
  static int num = 0;
  printf( "XYZZY DEBUG: initial num is %d\n", num);
  exit(1);

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

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.