C++ if statement

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;
cout << "It wasn't a perfect score" << endl;

Anyone know what I'm doing wrong?

3 answers Last reply Best Answer
More about statement
  1. Never mind I figured it out.

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

  2. Best answer
    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:

    if (100)

    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.
  3. Best answer selected by Gamerboy.
Ask a new question

Read More

Programming If Statement Apps