Error in declaration in Global Variable

Why global variable-value declaration has error before the main function "int a; a=10;" ??

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int a;
a=10;

int main(){
cout<<a;
}


Why the "a=10;" is error?Again:

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

int a=10;

int main(){
cout<<a;
}


has no error? And also:

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

int main(){
int a;
a=10;
cout<<a;
}


is correct?

Please explain.
You cannot do an assignation or call a function outside a function.
More details please.
First snippet line 5 is a stand-alone assignment statement. Executable statements are not allowed outside of functions.

Second snippet line 4 is an initialization of a global, which is allowed.

Third snippet - everything is within a function, which is fine.

Thanks.
Topic archived. No new replies allowed.