Gamerboy

Distinguished
Aug 13, 2010
36
0
18,580
I wrote this program to practice the if statement. I can't get it to execute the else statement. Regardless of what the user enters it executes the if statement.


//A program to let the user entera score and output if the score was perfect.

#include <iostream>

int main()
{
using namespace std;

cout << "Enter your programming class score" << endl << endl;

int x;

cin >> x;

if ( x = 100){
cout << "You got a perfect score!" << endl;
}
else{
cout << "It wasn't a perfect score" << endl;
}
system("pause");

Anyone know what I'm doing wrong?

Thanks.
 
Solution
In case you're wondering why what you did first behaved strangely: C++ treats any non-zero number as true, and zero as false. An assignment statement in C++ (like x=100) returns the value assigned, which is 100. You then effectively have an if statement that is like this:

Code:
if (100)
{
    foo();
}
else
{
    bar();
}

Since 100 is non-zero, it is evaluated as true. Because you have hard-coded the value being assigned, your if statement will always evaluate to true, and never touch the else block. If you had a zero instead of a 100, you would always go straight to the else block.

The revised if statement does a comparison rather than an assignment, and it simply returns true or false.

randomizer

Distinguished
In case you're wondering why what you did first behaved strangely: C++ treats any non-zero number as true, and zero as false. An assignment statement in C++ (like x=100) returns the value assigned, which is 100. You then effectively have an if statement that is like this:

Code:
if (100)
{
    foo();
}
else
{
    bar();
}

Since 100 is non-zero, it is evaluated as true. Because you have hard-coded the value being assigned, your if statement will always evaluate to true, and never touch the else block. If you had a zero instead of a 100, you would always go straight to the else block.

The revised if statement does a comparison rather than an assignment, and it simply returns true or false.
 
Solution