Sign in to follow this  
Genjix

Syntax weirdness

Recommended Posts

njpaul    367
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.

Share this post


Link to post
Share on other sites
Enigma    1410
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

Share this post


Link to post
Share on other sites
Genjix    100
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 :>

Share this post


Link to post
Share on other sites
Nathan Baum    1027
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this