0
what am I doing wrong...i have no clue. When I run it, it shows both outputs it's ok & double trouble...
#include <iostream> using namespace std; int main() { int girlsdumped; cin >> girlsdumped; if (girlsdumped=1) { cout << "it's ok" <<endl; } if (girlsdumped=2) { cout << "double trouble" <<endl; } return 0; }
6 Answers
+ 6
girlsdumped==1âŠâŠâŠ
+ 5
= assignment (setting value to var)
== equality
=== similar (equal value & type)
+ 2
why? what's problem with = sign?
+ 2
oo...Thanks
+ 2
@ValentinHacker, C and C++ don't have ===.
But yeah, = is always assignment (in which case the value returned is the value assigned) and == is comparison (the value returned is true or false, depending on whether the values converted to the same type are equal).
In the event where a direct comparison or implicit conversion can't be made, you'll get a compile error. Something I've seen coders do quite often to prevent mistakes like the above is use a constant on the left. The assignment will fail because obviously you can't assign a value to them, so the compiler will alert you to the issue instead.
if (1 == girlsdumped)
//etc. Yes, it does actually work.
0
I'm not sure what you mean by that. Sometimes you want an assignment in cases where a comparison is used. I often see something like the following to step through C strings:
char S[] = "Example";
char C;
while (C = *S)
{
//Process C
++S;
}
Mind you that's unsafe for modern usage due to potential lack of a null character causing buffer overreads but it demonstrates the usage nicely.