1

Why can I do

int x;

int main(){
    cout << x;
}

and it returns 0.

But when I do

int x;
x = 5;

int main(){
    cout << x;
}

I get an error?

edit: Turns out if I move all that inside my main() I can run it fine but I don't know why I can't put this initialization and assignment outside my main()?

ming
  • 229
  • 1
  • 9
  • you can, write `int x = 5;` outside `main` – fas Oct 17 '19 at 04:09
  • 2
    Statements (e.g. `x = 5;`) cannot appear outside of a function. Declarations and definitions can, though. Note that `int x;` is only a declaration and does not give `x` a value, unless it is of static lifetime. – iz_ Oct 17 '19 at 04:10
  • Oh, that's weird it was returning 0 for me so I assumed it just automatically assigned x = 0 upon initialization, is that not the case? @iz_ – ming Oct 17 '19 at 04:12
  • I know I can do that but why can't I just do what I did outside main as well? @user3365922 – ming Oct 17 '19 at 04:13
  • And why can't I have a statement outside of a function? – ming Oct 17 '19 at 04:13
  • Sorry, my bad, `int x;` will initialize `x` with `0` if `x` is static or global (like in this case). However, if you move `int x;` inside a function, it will not be given a value. In C/C++, the compiler executes code with an instruction pointer. If code is not organized into functions, the code will never run. – iz_ Oct 17 '19 at 04:19
  • *And why can't I have a statement outside of a function?* Thems the rules. I suspect this is done for organizational purposes, for example, when would this code be run? Would it be before or after similar global statements in other files? Sorta related: an integer with static storage duration will be initialized to zero if not specifically initialized. This is not true of an integer that is automatically allocated in a function. – user4581301 Oct 17 '19 at 04:21
  • can you comment what error you are getting? – Amal John Oct 17 '19 at 05:07
  • Different language but in this case also answering the question for C++: https://stackoverflow.com/questions/50661263/why-cant-i-assign-values-to-global-variables-outside-a-function-in-c/50661315 – Yunnosch Oct 17 '19 at 05:27
  • 3
    Possible duplicate of [Why can't I assign values to global variables outside a function in C?](https://stackoverflow.com/questions/50661263/why-cant-i-assign-values-to-global-variables-outside-a-function-in-c) – Yunnosch Oct 17 '19 at 05:28

0 Answers0