comparing boolean in if statement

why wont this work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main(){

    bool poop = false;
    
    if (poop=false){
        cout << "false";
        return 0;
    }else{
	cout << "true";
	}
    
    return 0;
}


i get the output as true even though its supposed to be false
It's (poop == false) not (poop = false) ;P!
= is used only for assigning whereas == is used only for comparing, remember! ;)

Also why have you used return 0; in the 'if block'? That will cause the main function to stop and return 0 to the operating system. You don't have to write anything the if statement will automatically stop in C++. ^_^

What is happening is that poop is getting assigned false within the if statement itself, and the if statement then checks the boolean value for poop (which counts as an expression as well) which is false by the time it is assigned. Cool huh.
Last edited on
The following is incorrect
 
if (poop=false)

When you have the above implementation, poop will be assigned with value "false" and thus the following will be executed.
 
cout << "true";


The correct one should be
 
if (poop==false)


This is a common mistake many people will do including me.
Thus, I will normally swap the position of the value and make it
 
if (false == poop)

so that the compiler will inform you on the syntax error.
Line 9
= != ==
@lastchance that expression (= != ==) will return true
It's true that it's not true that = is not the same as ==.

In other words,
= != == != == = == && = = = || == = == || = = =
I'll give you a cookie if you can put the above in a sentence.

Okay now I have officially blown your mind. Hooray!
Last edited on
Consider :

if (!poop) {}

is the same as

if (poop == false) {}
Topic archived. No new replies allowed.