0

everyone.

int x{};
if (x = 0) 
    std::cout << "condition true";
else
    std::cout << "condition false";

I didnt understand why x=0 evaluates to boolean false and executing "condition false". x=0 is an assignment,and x gets value of 0 so why it doesnt evaluate to true ?

smalcakmak
  • 27
  • 1
  • 9
    Why do you expect it to be true? – HolyBlackCat Aug 25 '22 at 07:03
  • 2
    if you write `x = 1` it'll yield `true`. This is basically the same for every other number. `0` is the numeric representation of `false` – DasSaffe Aug 25 '22 at 07:04
  • 2
    Do you expect assignments to return a value that indicates "successfull assignment" or something? – Lukas-T Aug 25 '22 at 07:05
  • This is explained in any beginner level [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and many related SO questions. Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and also refer to [what is return type of assignment operator?](https://stackoverflow.com/questions/15292892/what-is-return-type-of-assignment-operator) – Jason Aug 25 '22 at 07:11
  • *"x gets value of 0 so why it doesnt evaluate to true ?"* It does not evaluate to `true` **because** `x` gets the value 0. *Do you see why it helps to explain your reasoning? The answer to "why" is "because". However, if you explain your reasoning in greater detail, someone might be able to pick out the step where your reasoning goes off course.* – JaMiT Aug 25 '22 at 08:02
  • Zero values in C++ are *falsy*. Non-zero values in C++ are *truthy*. – Eljay Aug 25 '22 at 12:27

1 Answers1

12

The value of x=0 is that of x after the assignment. 0 is the only integer that when converted to bool is false.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185