Home > Software engineering >  My division function returns a zero. Should I declare x differently in main?
My division function returns a zero. Should I declare x differently in main?

Time:09-25

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

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related