Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | James Kuyper <jameskuyper@verizon.net> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: behavior of || operator |
| Date | 2011-10-07 14:11 -0400 |
| Organization | A noiseless patient Spider |
| Message-ID | <4E8F40BF.7000804@verizon.net> (permalink) |
| References | <j6nc0d$dii$1@speranza.aioe.org> |
On 10/07/2011 01:13 PM, Mark wrote:
> Hello,
>
> #define ATTACH 1
> #define DETACH 2
>
> #define DIRECTION_INGRESS 1 /* Incoming */
> #define DIRECTION_EGRESS 2 /* Outgoing */
>
>
>
> if ((action != ATTACH) || (action != DETACH))
>
> puts("invalid action");
This code is equivalent to:
if(action != ATTACH)
puts("invalid action");
else if(action != DETACH)
puts("invalid action");
Since ATTACH != DETACH, this is, in turn equivalent to:
puts("invalid action");
I don't think that's what you want to do.
> if ((dir != DIRECTION_INGRESS) || (dir != DIRECTION_EGRESS))
> puts("invalid direction");
>
>
>
> I appears that condition within if() is verified for being TRUE or FALSE,
> and it is sufficient to have just one operand of || operator to return TRUE
> in order for the whole expression yield TRUE result.
Yes, that's what || means: it either operand is true, the whole
expression is true.
> For example, if action = 1, then (action != ATTACH) becomes FALSE, then
> (action != DETACH) is evaluated and it will return TRUE, thus making the
> statement within if() TRUE. And this is wrong behavior, given that I need to
> have actoni be either 1 or 2.
>
>
>
> To make it right, || must be replaced with &&.
Yes:
if ((action != ATTACH) && (action != DETACH))
puts("invalid action");
is equivalent to:
if(action != ATTACH)
{
if(action != DETACH)
puts("invalid action");
}
Which seems a better fit to what I think you want.
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
behavior of || operator "Mark" <mark_cruzNOTFORSPAM@hotmail.com> - 2011-10-07 13:13 -0400 Re: behavior of || operator James Kuyper <jameskuyper@verizon.net> - 2011-10-07 14:11 -0400 Re: behavior of || operator John Gordon <gordon@panix.com> - 2011-10-07 18:47 +0000 Re: behavior of || operator Willem <willem@toad.stack.nl> - 2011-10-07 19:50 +0000 Re: behavior of || operator Gene <gene.ressler@gmail.com> - 2011-10-08 13:58 -0700
csiph-web