Reputation:
So I want an if statement to be like: if (foo == ("bar" | "barbar"))
. I think this is the bitwise OR operator, but I'm not sure. Anyways, this doesn't work. Any ideas on what I'm doing wrong?
Upvotes: 2
Views: 103
Reputation: 1149
As @cnicutar stated, the bitwise OR operator |
is not defined for string literals.
It seems to me that you're trying to execute code if foo is equal to either "bar" or "barbar". This would (note that this WILL NOT work) look like this (utilizing the standard, boolean OR operator, ||
):
if ((foo == "bar") || (foo == "barbar"))
This won't work (it will compile, but probably not do what you intended) because "bar" and "barbar" (and I guess foo, too) are character pointers, and this if statement would compare the ADDRESSES of these strings. What you would do is this:
if ((strcmp(foo, "bar") == 0) || (strcmp(foo, "barbar") == 0))
Note that you'll have to check whether the result of strcmp() is 0, as this denotes equality.
Upvotes: 2
Reputation: 21
The bit-wise OR operator does an OR operation on the individual bits in the values being ORed.
Examples: 0b10111001 | 0b01101101 == 0b11111101
uint8_t a = 0xF0;
uint8_t b = 0x0F;
uint8_t c = a | b; // This is 0xFF
In the case of literals, the value being operated on by the OR operator are their addresses and thus won't work how your code seems to intend.
As was stated in previous answers, you should use the strcmp
or strncmp
functions from the string.h
library to compare strings.
Upvotes: 0
Reputation: 122458
If you want to compare strings you need to use strcmp()
(manpage):
if (strcmp(foo, "bar") == 0 ||
strcmp(foo, "barber") == 0)
{
...
}
Upvotes: 1
Reputation: 182764
Anyways, this doesn't work. Any ideas on what I'm doing wrong?
The bitwise or operator isn't defined for string literals, so it makes no sense to use it in that context.
Upvotes: 1