0

I need some confirmation. I always get correct o/p but someone told me following expression will not work

Thanks in advance.

#define a 11

#define b 12

#define c 13     
    // I want if array[i] has values of any of these  then do something
    if( array[i] ==  (a) ||(b) ||( c))    
   // some function    
  else    
  printf("no match"); 
3
  • how would operator precedence play here? Commented Jul 21, 2011 at 15:16
  • 1
    Wouldn't the conditional always evaluate to true here? array[i] == (a) become a don't care because (b=12) != 0 which would yield true (same for (c) but the b condition would short-circuit)? It's been awhile since my C days... Commented Jul 21, 2011 at 15:19
  • @ Everyone... Thanks you all for helping me and clearing my doubts Commented Jul 21, 2011 at 15:29

4 Answers 4

2
 if (array[i] ==  a || array[i] == b || array[i] == c){
       ... 
   }

I do wish sometimes that you could say if (array[i] == [a, b, c]) or something to that effect.

Sign up to request clarification or add additional context in comments.

Comments

2

What you're doing is or'in the result of the boolean evaluation array[i]==a directly towards b, c.

In other words, ( (array[i] == a) || (b) || (c) ) is effectively what you're doing - probably not what you intended!

You will need to evaluate the boolean expressions separately:

(array[i] == a) || (array[i] == b) ...

2 Comments

To confirm my comment on the question: Since b != 0, the conditional would always be true -- correct?
Yep, looks to me like that's the case.
1

Replace your code with this:

if( array[i] == a || array[i] == b || array[i] == c)

Each part of the boolean condition must be a complete expression. While what you wrote is valid C code, it doesn't achieve what you want: you need to make an array element comparison in every part.

2 Comments

Thanks for the explanation. I will try and let you guys know
--> Thanks for quick and efficient reply.
0

"Someone" is correct. You need to use:

if ((array[i] == a) || (array[i] == b) || (array[i] == c))

Your program does not always produce correct output. Try it with any i not equal to 11, 12, or 13.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.