[SystemSafety] A small taste of what we're up against

Olwen Morgan olwen at phaedsys.com
Sun Oct 21 16:46:27 CEST 2018


Here's another WTF program in C:

#include <stdio.h>

int incr(int n) { return n+1; }

int main(void)
{
     char a[2] = {'R', 'R'};
     int  i    = 0;

     char b[2] = {'R', 'R'};
     int j     = 0;

     a[i] = (++i, 'L');
     b[j] = (incr(j), 'L');

     printf("Evaluation of = in \"a[i] = (++i, 'L');\" is %c%c\n", a[0], 
a[1]);
     printf("Evaluation of = in \"b[j] = (incr(j), 'L');\" is %c%c\n", 
b[0], b[1]);

     return 0;
}

compiling under either of gcc 5.4.0 or clang-4.0 and then running gives:

... Evaluation of = in "a[i] = (++i, 'L');"     is RL
... Evaluation of = in "b[j] = (incr(j), 'L');" is LR

both gcc and clang warn of multiple side effects in the assignment a[i] 
= (++i, 'L');

for the same line cppcheck produces the warning:

... test-ccpcheck-4.c:13: error: Expression 'a[i]=++i' depends on order 
of evaluation of side effects

Both gcc and clang are clearly capable of evaluating the operands of the 
= operator in different orders in the same program depending on the form 
of the RHS of the assignment (presumably owing to optimisations). And 
cppcheck diagnoses the offending text as "a[i]=++i'", which isn't even 
what was written!

The C standard permits the compilers to do what they are doing here. The 
only way a static analyser can cope with this is to check under every 
order of evaluation that the compiler permits. I'm not aware of any that 
do that for C but AFAI am aware the SPARK tools do it for Ada.

Perhaps the return statement above should have read: return 60||0x02c;


:-) Olwen




More information about the systemsafety mailing list