What is wrong with this code..?

This is going to be utterly stupid I am sure of it.. The code the way it is written is not allowing for the else statement and is always evaluating to 'true'
however my compiler says there is no errors found.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
using namespace std;

bool IsEven()
{

    // if x % 2 == 0, 2 divides evenly into our number
    // which means it must be an even number
    int x;
    if (x % 2 == 0)
        return true;
    else
        return false;
}


main()
{

cout << "What will x be?" << endl;
int x;
cin >> x;

if (IsEven())
cout << "Your number was even!" << endl;

else
cout << "Your number was odd!" << endl;


}

Last edited on
The x in your main function has nothing in common with the x you declared in your isEven function.
The x in your IsEven function is uninitialized and therefore causes undefined behavior that you can't rely on.

in other words,
I would pass your x variable into your function as a parameter instead:
1
2
3
4
bool IsEven(int x)
{
    return x % 2 == 0;
}
Last edited on
I see what you're saying, my compiler is now telling me I do not have enough arguments in the function? (I am using code::blocks)
Oh, if you are now using the function I wrote above, you now have to pass the variable you want to check into the function you made.

1
2
3
4
int x;
cin >> x;
if (IsEven(x)) // x is being passed to your IsEven function
    cout << "Your number was even!" << endl;
Last edited on
IsEven function doesnt make any sense til you put parameter on it for passing the reference on x , on main function, which reads input on this program.
Topic archived. No new replies allowed.