Elliot Gorokhovsky
Elliot Gorokhovsky

Reputation: 3762

Unique ids using a static variable in C

I need to give certain nodes in my tree unique ids as they are recursively added. I wrote code like this to solve the problem:

  } else if (deapTree[0] == -1){
    static int const_idx;
    //bla bla bla
    root->idx = const_idx;
    //bla bla bla
    const_idx++; 
  } else {

Will this work as I intend? Meaning const_idx will start at 0, and then every time that branch of the if is reached it'll get incremented by 1.

Upvotes: 1

Views: 47

Answers (2)

o11c
o11c

Reputation: 16136

This will work for single-threaded programs. For multi-threaded programs, you need to use _Atomic.

That said, I recommend refactoring it out to a separate function.

Alternatively, consider moving the counter from a global variable to a member of the tree root itself.

Upvotes: 2

Amit Kumar
Amit Kumar

Reputation: 59

Yes, it will work as expected.

Upvotes: 1

Related Questions