0

about "==" and "=" in if statement

I have found a problem that "==" and "=" is very different in if statement. For example, if there's a variable "a" I type in some code : if ( a == n ) ; { action1 } if (a = m ) ; { action2 } the first block is able to work normally,but the other will always be executed. what are the differences between them? hope that I can get your help.Thanks a lot :) ----from a Chinese starter

11th May 2018, 4:26 PM
HZCK_Mi Sa Pon
HZCK_Mi Sa Pon - avatar
6 Answers
+ 1
= is an assignment opperator. == is a conditional operator, it tests for equality. 'if' statement in C++ does not accept only conditional expressions inside the parentheses. It will consider expressions that return zero and false as 'false'. Everything else is 'true'.
11th May 2018, 4:48 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 3
Firstly never ever use = in if statements the assigning operator is only used to assign values to objects/variables, always use ==. I think whats happening is that C++ checks if the assigning was successful if it was then it returns true executing the if block of code.
11th May 2018, 4:32 PM
TurtleShell
TurtleShell - avatar
+ 2
== tests for equality = assigns the value on the right side to the variable on the left, the result is the value assigned when the result of condition is non-zero, it is true otherwise it is false
11th May 2018, 5:06 PM
michal
+ 1
TurtleShell There many examples in which you would want to use = inside an if statement. For example: if ((c = getchar()) == EOF) { //end } else { //go on with c as the next char } Misapon It's also worth noting that if (a = 0) always executes.
11th May 2018, 4:53 PM
Vlad Serbu
Vlad Serbu - avatar
+ 1
Vlad Serbu I have to desagree with you in the last point. if(a = 0){ // this will not execute } https://code.sololearn.com/cYqvvmBZUAHZ/?ref=app
11th May 2018, 5:00 PM
Ulisses Cruz
Ulisses Cruz - avatar
0
I don't know how to give thanks to each of you in this app,so I thank all of you here for your great help to me :)
12th May 2018, 5:46 AM
HZCK_Mi Sa Pon
HZCK_Mi Sa Pon - avatar