Defining and Declaring global variable in C++

75 Views Asked by At
#include <iostream>
using namespace as std;

int x;
x=10;

int main()
{
 cout<<x<<endl;
 return 0
}

This gives an error, but if I use:

int x=10;

instead of:

int x;
x=10;

It works fine. Can anyone point out the issue? The compiler reads error:

expected constructor, destructor, or type conversion before '=' token compilation terminated due to -Wfatal-errors.

1

There are 1 best solutions below

2
On

Out of the body of function you can only declare (int x;) or declare and initialize (int x = 10;) variables. Here you were trying to assign a value (x=10;) to variable that was declared before.