Self-referential initialization

R

Risto Lankinen

Hi!

Is the following construct legal in C++?

int i = i;

It seems to be working on the compilers that I have. If it
indeed is legal, what is the rationale?

Note also that the following very dangerous construct, too,
seems to be working (probably for the same rationale):

int &r = r;

Cheers!

- Risto -
 
T

tom_usenet

Hi!

Is the following construct legal in C++?

int i = i;

It is well-formed (it should compile), but executing it leads to
undefined behaviour, since you are initializing an int with an
indeterminate int value.
It seems to be working on the compilers that I have. If it
indeed is legal, what is the rationale?

The declaritive scope of a variable starts after its declarator but
before its initializer. I suppose it allows things like:

struct A
{
A(A* other);
};

A a = &a;

which might be useful to someone (although I'm not sure that it is
legal).
Note also that the following very dangerous construct, too,
seems to be working (probably for the same rationale):

int &r = r;

Again, well formed, but illegal.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top