Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if variable equal to multiple values

In C I want to check if variable equal to multiple values and I don't know how to code it without separating it fully.

if (str[i]=='u'||'o'||'i'||'e'||'a') giving me always true and I don't understand why, I need explanation.

if (str[i]==('u'||'o'||'i'||'e'||'a')) giving me always false and I don't understand why, I need explanation.

thanks.

like image 452
Ghnb Trcv Avatar asked Feb 16 '26 04:02

Ghnb Trcv


1 Answers

The reason why the following expression is always returning true:

if (str[i] == 'u'||'o'||'i'||'e'||'a')

is that character constants evaluate to true. So, the above is really the same as this:

if (str[i] == 'u'|| 1 || 1 || 1 || 1)

What you intended to do is this:

if (str[i] == 'u' || str[i] == 'o' || str[i] == 'i' || str[i] == 'e' || str[i] == 'a')

Note that the equality expression needs to be repeated for each comparison.

like image 195
Tim Biegeleisen Avatar answered Feb 18 '26 18:02

Tim Biegeleisen