Re: [OxLUG] Logical operator precedence in C

Top Page
Attachments:
Message as email
+ (text/plain)
Delete this message
Reply to this message
Author: Carsten Agger
Date:  
To: chris@chriswareham.net, Oxfordshire Linux User Group Discussion List
Subject: Re: [OxLUG] Logical operator precedence in C
Hi

You're quite right! This is how I'd do it:

if(
     exposed->line_exposed[cursrow] ||
      (
       ((cursor & LIGHTCURSOR) && exposed->line_exposed[cursrow + 1]) ||
       (cursrow > 0 && exposed->line_exposed[cursrow - 1])
     )
)


Best
C

On 08/28/2015 02:16 PM, wrote:
> Hi folks,
>
> Trying to update some ancient C code, and GCC is suggesting:
>
> csr_change.c:516:41: error: suggest parentheses around ‘&&’ within ‘||’
> [-Werror=parentheses]
>                   ((cursor & LIGHTCURSOR) && exposed->line_exposed[cursrow + 1]
> ||

>
> The code in question is:
>
>          if((exposed->line_exposed[cursrow]) ||
>                  ((cursor & LIGHTCURSOR) && exposed->line_exposed[cursrow + 1] ||
>                   (cursrow > 0 && exposed->line_exposed[cursrow - 1])))

>
> I always struggle with the precedence of && and || in C (the
> former has higher precedence), or more accurately I struggle
> with the consequences of that precedence on code like the above.
> Am I right in thinking that the parentheses to make this
> statement clearer should be:
>
>          if((exposed->line_exposed[cursrow]) ||
>                  (((cursor & LIGHTCURSOR) && exposed->line_exposed[cursrow + 1])
> ||
>                   (cursrow > 0 && exposed->line_exposed[cursrow - 1])))

>
> My brain is turning to jelly trying to work this out :-(
>
> Chris
>
>
>