// if statement
#include <iostream>
usingnamespace std;
int frenchfries = 45;
int main()
{
if (true)
cout << "This is always displayed.\n\n";
if (false)
cout << "This is never displayed. \n\n";
if (frenchfries = 50)
cout << "You have 50 french fries.\n\n";
if (frenchfries == 500)
cout << "Wow, how did you get so many french fries?\n\n";
// using (frenchfries = 50) on line 17 instead of (frenchfries == 50)
cout << "frenchfries is: " << frenchfries;
cin.get();
return 0;
}
I thought it was interesting that even though I had written "(frenchfries = 50)" to be interpreted as a condition, C++ also redefined the number of french fries as well as still considering its boolean value.
To test this theory I wrote cout << "frenchfries is: " << frenchfries; at the end of the program and am glad to know that this is indeed correct.
Program result:
This is always displayed
You have 50 french fries.
frenchfries is:50
Nope. The = operator is used only for assignment, and it returns a reference to the variable. For example:
(var = 50) = 40;
This first assigns 50 to var, returns a reference to var, and then assigns 40 to that reference (var).
Here's another example:
var1 = var2 = 3;
This first assigns 3 to var2, which returns a reference to var2 and assigns the value of var2 to var1.
In C++ any non-zero value is true, so ofc 50 is true.
Yes, unfortunatly C++ allows assignments within the if clause. Like stated before everything that's not 0 is interpreted as true else false. The assignment or what ever is executed.
This if (frenchfries = 50) is really this
1 2
frenchfries = 50;
if(frenchfries != 0)
Becaus of this vulnerability i use the constant value first, like: if (50 == frenchfries)