0

I was doing an assignment where this problem in a different scenario occurred (Actually I was trying to use a user defined class pointer in the same way, and it took me a long time to find the problem). I'm giving code snippets below:

#include<iostream>
using namespace std;

// int x = 5; this line works just fine
//whereas the below two lines don't
int x;
x = 5; //red squiggles here, under x. The error reads: this declaration has no storage class or type specifier

int main()
{
    //x = 5; this line works too
    cout<<x<<endl;
}

I know this might be a very basic question, but I'm still a beginner. Can someone explain to me why declaration in the global scope of a variable does not work? (I'm assuming the variable does not get a memory space until the main function starts, is it so?) I googled the problem, but couldn't find any good answers. Your help would be much appreciated TIA ^-^

  • 3
    The declaration/definition is fine. It's the assignment outside of a function that isn't. What's the purpose of trying to assign a value afterwards? You can call a function if you need some logic for the assignment: `int x = []{ return 5; }();` – Ted Lyngmo Apr 24 '21 at 10:23
  • 2
    At the "top level", you can only have declarations and definitions. – molbdnilo Apr 24 '21 at 10:30
  • Works kinda the same as in C, I guess this might help: https://stackoverflow.com/questions/50661263/why-cant-i-assign-values-to-global-variables-outside-a-function-in-c – Fёdor Makhnach Apr 24 '21 at 10:30
  • Note to self: "_if you need some logic for the assignment_" should be "_if you need some logic for the initialization_". – Ted Lyngmo Apr 24 '21 at 10:38

0 Answers0