Search code examples
cmisra

Sizeof compound literal array producing side effects?


  1. Does sizeof((int[]){1,2,3}) get evaluated at compile time? And is guaranteed by the standard.
  2. Does the sizeof operand in this case produce side effects?

I am asking this question because with Tasking compiler this line results in warning "side effects of 'sizeof' operand are ignored".
I am wondering if this is a spurious warning or is there something to it.

I am trying to be compliant with MISRA rule 13.6 that states "The operand of the sizeof() operator should not contain any expression which has potential side affects".


Solution

    1. Does sizeof((int[]){1,2,3}) get evaluated at compile time? And is guaranteed by the standard.

    The spec does not say, but probably so. This is in any case not directly relevant to MISRA 13.6

    1. Does the sizeof operand in this case produce side effects?

    No, not as far as the spec is concerned. The expression (int[]){1,2,3} produces a value when evaluated, but the language spec does not describe any side effects (producing a value is not itself a side effect). Contrast with i++, which both produces a value and has a side effect of modifying the stored value of i.

    Note well that the operand is not evaluated at all, as other answers also observe, but that's the point of the MISRA rule. It wants you to avoid sizeof() operands that would have side effects if evaluated, because it may be surprising that the operand isn't actually evaluated, and therefore the side effect does not occur.

    I am asking this question because with Tasking compiler this line results in warning "side effects of 'sizeof' operand are ignored".

    I am wondering if this is a spurious warning or is there something to it.

    If MISRA is to be read as talking about side effects defined by the language spec then the warning is definitely spurious.

    If MISRA were read as talking about side effects produced by a particular C implementation, including any not defined by the language spec, and if in your particular implementation, evaluating a compound literal did produce a side effect, then the warning would not technically be spurious. But this seems a combination of a questionable reading and an unlikely behavior. Moreover, even in this case, I'd say that the warning could probably be ignored without violating the spirit of the rule, because no one is going to be confused about a side effect not happening that they weren't expecting anyway.