Home > Back-end >  How to use an OR function with chars correctly in C?
How to use an OR function with chars correctly in C?

Time:10-16

First question! Very new to programming. I am looking to print an asterisk whenever a player has entered either 'a' or 'b' after a get_string function. Running this code and entering either 'a' and 'b' does not produce an asterisk whereas entering 'c' does produce an asterisk.

  1. Why does it produce an asterisk only for the 'c' input?

  2. What is the correct way to use of the OR function here?

Thanks for your help!

for(int i=0;i<strlen(input);i  )
    {
        if (input[i] == ('a' | 'b'))
                {
                    printf("*");
                }
    }

CodePudding user response:

If you have more characters to look for then a chain of || is getting cumbersome. Alternatively you can use strchr.

if (strchr("ab", input[i]))

CodePudding user response:

What is the correct way to use of the OR function here?

Like this:

if (input[i] == 'a' || input[i] == 'b')

Why does it produce an asterisk only for the 'c' input?

I suggest reading about what the | operator does. It is the bitwise or operator, which is different from || which is the logical or operator. You can read about it in another answer I wrote. Also, character literals like 'a' are just plain integers in disguise.

CodePudding user response:

The correct syntax is

for(int i=0;i<strlen(input);i  )
{
    if (input[i] == 'a' || input[i] == 'b')
    {
        printf("*");
    }
}

What you're currently doing is bitwise-ORing 'a' and 'b' (which evaluates to 99 (the ASCII character c)), and comparing the value to that.

  •  Tags:  
  • c
  • Related