Syntax weirdness

Started by
5 comments, last by Nathan Baum 18 years, 4 months ago

int x(x = 10);
umm... how can I assign 10 to x when x isn't constructed yet?
Advertisement
I've never seen that syntax before (and indeed when I use it, it doesn't compile), but I have seen and used

int x(10);


Its like calling a constructor for the int and passing it the value you want it to be.
Technically speaking, how can you give something some value if it doesn't exist, what the previous poster said is correct.

ace
Its possible. Try this:


void main()
{

int x = 1;

{
int x (x=10);
}
}


Notice the inside "{","}" block.
That statement on its own is not legal. In some contexts however it can be legal, for instance:
int x;int main(){	int x(x = 10);}

Here the line int x(x = 10); defines a local variable x initialised to the result of assigning 10 to the global variable x.

Enigma
well on g++ this is what I wrote... and it compiled without error giving output of 10
#include <iostream>int main(){        int x(x = 10);        std::cout << x << "\n";        return 0;}


Can anyone explain this strangeness? To me this doesn't seem legal.

If this is a g++ bug it isn't the first time this has happened to me :>
It's perfectly valid.

The C++ standard says:

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

x is in scope when (x = 10) is evaluated, and any expression is permitted in a paranthesised initialiser.

This topic is closed to new replies.

Advertisement