My division function returns a zero. Should I declare x differently in main?

#include <iostream>
using namespace std;

int division(int c, int d);

int x = 2;
int y = 2;

int division(int c, int d)
    return (c/d);

int main()
    cout << "Hello World!n";
    int x = division(x,y);
    cout << x;
    return 0;

I expected the code to show 1 after Hello World!, but it prints 0.
I removed int from in front of x (in main()) and ran it again and it returned 1.
But I also passed x,x to the division function with the int in front of x (in main()) and it returned 1.

So I am not sure how the assignment statement is working.


This expression:

int x = division(x,y);

is equivalent to writing this:

// 'x' was defined globally somewhere here before
int x;
x = division(x, y);

This shadows the previous x variable defined globally and defines a local variable x which again is uninitialized so after passing it in the division() function, your code has Undefined Behavior. (When that happens, the output can be anything, it can be 0, it can even be 1 or something else entirely.)

What you want to do is to remove the declaration and turn it into an assignment instead:

x = division(x,y);

Then the above works properly and gives 1.