Manish Kumar Singh
Manish Kumar Singh

Reputation: 183

Defining and Declaring global variable in C++

#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.

Upvotes: 1

Views: 59

Answers (1)

Krzysztof Sawicki
Krzysztof Sawicki

Reputation: 414

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.

Upvotes: 2

Related Questions