Relational Operators and Arrays

Why doesn't my code print out "Wow"? I know it is a simple question but I think there is an important lesson that needs to be learned here about the nature of relational operators and arrays. If you can answer this question, that would be awesome. Thank you and have a great day!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std; 



int main() 
{
	int array[3] = {1, 2, 3}; 
	if ((array[0] && array[1] && array[2]) == (1 && 2 && 3))
	{
		cout << "wow" << endl;
	}

return 0; 
}
Last edited on
You didn't get it quite right. It should be like array[0] == 1 && array[1] == 2 && array[2] == 3
Your problem is that this will never result in a true expression. Your testing whether array[0] == 1, 2, and 3 AND array[1] == 1, 2, and 3 AND array[2] == 1, 2, and 3. Instead test
1
2
if((array[0] == 1) && (array[1] == 2) && (array[2] == 3))
//then your test will evaluate to true and you will print out "wow" 
If it doesn't print out "wow", then you probably have an issue with your console window not staying open.


OUIJ wrote:
Your problem is that this will never result in a true expression.

The expression in question will always evaluate to true.


OUIJ wrote:
Your testing whether array[0] == 1, 2, and 3 AND array[1] == 1, 2, and 3 AND array[2] == 1, 2, and 3.

Incorrect.

The expressions (array[0] && array[1] && array[2]) and (1 && 2 && 3) are completely unrelated and unconnected to each other. The first expression always evaluates to true since each element of the array is non-zero. The second expression always evaluates to true since each value is non-zero. Put those two together and we have if ( true && true ) which, again, is always true.
Thank you guys. Very helpful. I see my mistake now.
Topic archived. No new replies allowed.