Different approaches taken by C and C++ to initialize static variable

Hi all:

Please read out these following 2 code snippets
1
2
3
4
5
6
7
void sub()
{
  int i = 1;
  //i =1;
  static int* q =&i;
 
}

Compiled using gcc yields:

In function ‘sub’:
error: initializer element is not constant


1
2
3
4
5
6
7
void sub()
{
  int i = 1;
  //i =1;
  static int* q =&i;
 
}

If compiled using g++,all goes fine.

the initial value of q must be known before the program starts to

run. But now the initial value is the address of an automatic variable.

Automatic variables don't exist until the function is called. There is no way

to know what the address will be of something that doesn't exist yet.


So why this could pass the compilation phase using g++.
In C++, local static objects are constructed on first use, not at program startup. So this works just fine.

In C, apparently all static objects are constructed on startup, which is why you get the error.


Note that having a static pointer that points to a non-static local is probalby a very, very bad idea.
Gotcha, so it is the language difference. Thanks a lot.
one more thing i want to mention do not use above style in coding .....there may be some memory corruption .....as int i is local variable which got space in stack area and get destroyed after return.But static variable does not.
Topic archived. No new replies allowed.