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

Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
  • The call to `division` isn't operating on the data you think it is. Try renaming the `int x` in `main` to `z`. – jkb Sep 25 '21 at 03:51
  • Useful reading, almost duplicate https://stackoverflow.com/questions/9820027/using-newly-declared-variable-in-initialization-int-x-x1 – 273K Sep 25 '21 at 04:08
  • Check this out, https://www.tutorialspoint.com/cprogramming/c_scope_rules.htm – SaminatorM Sep 25 '21 at 13:10

2 Answers2

2

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.

Ruks
  • 3,886
  • 1
  • 10
  • 22
2

You should compile your code at least with -Wall flag.
You would then see a helpful warning message:

foo.cpp: In function ‘int main()’:
foo.cpp:17:21: warning: ‘x’ is used uninitialized [-Wuninitialized]
   17 |     int x = division(x,y);
      |             ~~~~~~~~^~~~~

It means that to the division() isn't passed global x, but the local one from main().
It's undefinied behaviour, no different than int z = division(z,y);

After removing int from before x in main() you no longer declare local variable, thus there is only one x in your program (the global one) and from initialization the line turns into plain assignment.

Jorengarenar
  • 2,705
  • 5
  • 23
  • 60