small question about if and else

Hello everybody.
I'm having a little problem, when I start debugging no matter what value I assign x it always says "correct". However I specified that it should display that message only when x=5
Here is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
 
int main()
{
 using namespace std;

 double x;
 cout<<"x = ";
 cin>>x;


 if( x = 2 + 3)
 {
		  cout<<"correct"<<endl;
 }
 else {
	 cout<<"wrong";
 }

 system("pause");

}

What seems to be the problem?
You aren't testing if x == 5. One = is the assignment operator. What you are doing is assigning the value of 2 + 3 to x. Then testing the value of x, which is 5. Since 5 is not 0, it is true, and this outputs your "Correct" string. To compare the value of x is equal to 5, you use the equals to operator, or ==.

Also, and a minor note, but you are using two different formatting styles for your braces. The if statement has bother of its braces on the same line as the if statement. I use this style myself as it kind of helps me keep track of which blocks belong to with loops and such. But the else statement has the open brace with the else statement. Both are valid and widely used forms, and not really a big deal on a simply program like this, but when you get into larger programs with multiple nested if and loops and such it can have a huge impact on readability using different styles.
Last edited on
Ah yes, Forgot about that, Thank you Raezzor!
No problem! I'm sure everyone on this board has made that or similar mistakes before. I know I sure have. At least you'll definitely be looking for it in the future!
Topic archived. No new replies allowed.