-2

I have a question:
Why does (a == b == c) inside if statement in C not work?

For example, I have this code:

int naxes1[1] = {6};
int naxes2[1] = {6};
int naxes3[1] = {6};

if (naxes1[0]  == naxes2[0] == naxes3[0])
    printf("first doesnot work\n");

if (naxes1[0]  == naxes2[0] && naxes1[0]== naxes3[0])
    printf("second works\n");

why?

I went through following links:
Usage of greater than, less than operators

Community
  • 1
  • 1
BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169
  • Simply change the programming language. AFAIK in JavaScript you may use operator ===.:) – Vlad from Moscow Aug 07 '15 at 14:54
  • @VladfromMoscow: The question isn't about `===`, it's about `a == b == c`. Which doesn't work in JavaScript, either (except with booleans, like C). – T.J. Crowder Aug 07 '15 at 14:56
  • @Quentin: This is my point, you can do it if you have booleans (and you pick the right values), but it's unlikely to be what you actually wanted. – T.J. Crowder Aug 07 '15 at 15:23
  • @T.J.Crowder that's an original definition of "works", I guess :p Note that it will actually compile for a great variety of types, provided there's an implicit conversion from `bool`. – Quentin Aug 07 '15 at 15:26

2 Answers2

4

Because it's evaluated like this:

if ((naxes1[0] == naxes2[0]) == naxes3[0])
//  ^----------------------^---- Note

...and the result of that inner expression isn't the value in naxes1[0] or naxes2[0], it's a boolean.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

Order of operations. The first == will result a true or 1. then when you compare 1 to naxes[0] you get

1 == 6

which is false so you get 0 and it does not print.

ameyCU
  • 16,489
  • 2
  • 26
  • 41
Dan
  • 383
  • 1
  • 4