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; }

7th Jan 2017, 1:44 PM
Shivoham Shivam
Shivoham Shivam - avatar
6 ответов
+ 6
girlsdumped==1………
7th Jan 2017, 1:45 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 5
= assignment (setting value to var) == equality === similar (equal value & type)
7th Jan 2017, 1:49 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 2
why? what's problem with = sign?
7th Jan 2017, 1:47 PM
Shivoham Shivam
Shivoham Shivam - avatar
+ 2
oo...Thanks
7th Jan 2017, 1:51 PM
Shivoham Shivam
Shivoham Shivam - avatar
+ 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.
7th Jan 2017, 3:58 PM
Nemo
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.
29th Jan 2017, 2:35 AM
Nemo