简体   繁体   中英

Difference between =, ==, != in c++

I just started c++ a few days ago on Codecademy and couldn't really find the answer to this question. I know that in other programming languages "=" means "to assign" a value to, and "==" means "to check if two values are equivalent". When I was using if statements with bools, I noticed that I could not do

bool a = false;
if (a = true) {
  std::cout << "a is true!\n";
}

as I needed a == for the if statement to work, as it would print regardless of what the bool actually was. But when I did the same thing and put a as an integer, it worked.

int a = 1;
if (a = 1) {
  std::cout << "a is equal to 1\n";
}

while

int a = 0;
if (a = 1) {
  std::cout << "a is equal to 1\n";
}

would not print. Is this only for integers or is bool the odd one out? Also does "?=" mean an incorrect comparison or would I have to use something like "?=="? Does "===" exist in c++ like it does in some other programming languages?

int a = 0; if (a = 1) { std::cout << "a is equal to 1\n"; }

would not print.

Your assumption is incorrect. The quoted program prints.

Does "===" exist in c++

It does not exist in C++.

Difference between =, ==, != in c++

= is the assignment operator. == is the equality operator. != is the inequality operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM