Sign in with
Sign up | Sign in
Your question
Solved

C++ if statement

Last response: in Applications
Share
April 27, 2012 3:43:36 PM

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.

More about : statement

April 27, 2012 5:12:04 PM

Never mind I figured it out.

I switched if ( x = 100) for if (x == 100).

Thanks.
m
0
l

Best solution

a b L Programming
April 28, 2012 12:33:23 AM

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:

  1. if (100)
  2. {
  3. foo();
  4. }
  5. else
  6. {
  7. bar();
  8. }


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.
Share
April 28, 2012 6:22:01 PM

Best answer selected by Gamerboy.
m
0
l
!