Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of Objects with Static Storage Duration in C vs C++ [duplicate]

Possible Duplicate:
What does main return?

For example, the following code compiles without any warning:

#include <stdio.h>

int i = i + 1;

int main(int argc, char *argv[])
{

    fprintf (stderr, "%d\n", i);

    return 0;
}

I think this is illegal in syntax, because i is used before it's declared, is it right?

And in my opinion, the appearance of int i = i + 1; is surely a bug, why doesn't the compiler warn about it? I use gcc 4.5.1.

like image 234
fool Avatar asked Mar 29 '11 14:03

fool


2 Answers

(notice: I'm referring to the current C++ standard)

I'm not really sure about this, but, if my interpretation of the standard is correct, the code should be fine and not UB.

The first initialization of that variable is the zero-initialization of objects with static storage duration that happens before any other initialization takes place (§3.6.2 ¶1).

So, first of all i is set to zero.

Then, dynamic initialization (i.e. non-zero and non-constant initialization) takes place, so it uses the current value of i (0) to actually initialize it again. At the end it should evaluate to 1.

This seems confirmed by §8.5 ¶6, that explicitly says:

The memory occupied by any object of static storage duration shall be zero-initialized at program startup before any other initialization takes place. [Note: in some cases, additional initialization is done later. ]

(If you find some flaw in the analysis please just tell me in the comments and I'll be glad to correct/delete the answer, it's slippery floor and I'm conscious of it :) )

like image 54
Matteo Italia Avatar answered Oct 07 '22 17:10

Matteo Italia


In C++ it is syntactically correct. In C you can initialize a global variable only with a constant. So your code would not compile in C.

In C this is legal BTW

int main()
{
   int i = i+1;
}

3.3.1/1 Point of declaration

The point of declaration for a name is immediately after its complete declarator and before its initializer (if any).

The behaviour is well defined as per §3.6.2/1 which says:

"Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place."

like image 44
Prasoon Saurav Avatar answered Oct 07 '22 18:10

Prasoon Saurav