'if' function rookie question

I was messing around with if function so I ended up with the code below

1
2
3
4
5
6
7
8
9
 #include <iostream.h>

int main()
{
	int x = 4;
	if (x = 70 && x == 4)
		cout << x;
		else cout <<"nope";
}


Why does it return 1 as x value?
Why does it give me a compilation error when swapping places x = 70 and x == 4 in lane 6?
Turn on warnings
 In function 'int main()':
6:22: warning: suggest parentheses around assignment used as truth value [-Wparentheses]

Your code is doing: if (x = (70 && (x == 4))).

Logical AND has higher precedence than assignment, so it's doing
(x = (70 && (x == 4))) (an assignment).
x is 4, so (70 && true) is true, which then gets converted into 1.

Also, just from the fact that you are using <iostream.h>, a non-standard header, means that you're using an extremely old compiler. I would suggest updating to something made at least within the last decade, e.g. GCC, Clang, or Visual C++.
Last edited on
if is not a function, though in many ways it can look like one at times.

x can never be both 70 and 4 at once, so when you 'fix' it, you will always get false instead of always getting true. x can be (70 OR 4) and that makes some sense. C++ is a little weird to get used to & vs && and = vs == etc in comparisons, but you will soon find them second nature. Single &, | are bitwise, double are logical. Usually you want logical, bitwise is occasionally handy for something like even/odd check (& 1, check if the least significant bit is 0 or 1 where 1 is odd and 0 is even), so you will rarely want single & or single | in your early coding efforts.

current compilers do mostly take <iostream.h> if you don't tell them not to with strict options, and they may warn, but it still usually works. Still, do what he said, even if it accepts it that is pre 1998 C++ style. Its just <iostream>. There are 2 patterns for standard includes: drop the .h, or drop the .h and put C in front of it ( <cmath> was <math.h> )
Last edited on
#include <iostream.h>
Notwithstanding jonnin's post, you're probably doing yourself a major disservice by learning an obsolete tool.
Last edited on
Topic archived. No new replies allowed.