0

Why should this be an error?

int a = 0; a = 42; int main() { } 

A possibe match for this behavior i could find:

(3.4.1/4) A name used in global scope, outside of any function, class or user-declared namespace, shall be declared before its use in global scope.

Could this be a defect in standard?

4
  • No, it's not a defect to the standard. The part you quote means you need to have declarations for all the names you want to use before you use them. It doesn't mean you can do whatever you want at global scope. Commented Nov 1, 2011 at 11:32
  • What does it mean by before you use them in global scope? Commented Nov 1, 2011 at 11:40
  • struct A {}; A foo(); The name A is used in the declaration of foo(). Commented Nov 1, 2011 at 11:42
  • @user974191, you can use it as follows: int b = a + 1;. Commented Nov 1, 2011 at 11:43

2 Answers 2

7
int a = 0; //it is a declaration (and definition too) statement a = 42; //it is an assignment statement 

The second line is the cause of error, for it is an assignment statement.

At the namespace-level, only declaration and definition statements are allowed. Assignment-statements are not allowed at namespace level.

And by "shall be declared before its use in global scope" (from the spec's quotation) means the following:

int a = 42; int b = 2 * a; //a is being used here int c = a + b; //both a and b are being used here 

If you define type instead, then:

struct A {}; //definition of A struct B { A a; }; //a is declared as member of B //(which means, A is being "used") void f(const A&, const B&); //both A and B are used in the declaration of f 
Sign up to request clarification or add additional context in comments.

7 Comments

Well, it's an expression statement, to be precise. Assignment is an expression, not a statement.
@CatPlusPlus: If one includes ;, then it becomes statement.
Yes, an expression statement.
@CatPlusPlus, expression statement is not an expression though.
@avakar: Good lord, where did I say it's an expression. I think I named it a statement at least twice.
|
1

You cannot write an assignment statement like that in the global namespace

it needs to be either in main or in some [member] function

int main() { a=42; return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.