Home > Net >  Which form is better for return value of functions in embedded C?
Which form is better for return value of functions in embedded C?

Time:01-13

I am working on embedded C. Could somebody help me which piece of code?

Is efficient in terms of robustness, memory as well as Misra friendly?

Code1:

if (func() == 1 || func() == 2) {
    /* Body of the function */ 
}

Code2:

locvar = func();

if (locvar == 1 || locvar == 2) {
    /* Body of the function */    
}

CodePudding user response:

As noted, the two examples may do different things and give different results.

MISRA-C compliance and robustness go hand in hand. As for memory use, it's not an issue in this code.

The first example is likely not robust nor MISRA compliant: specifically, MISRA-C:2012 rule 13.5 bans the right operand of && and || from containing persistent side effects.

Furthermore, rules like 12.1 requires sub expressions of large expressions to be surrounded by parenthesis, to make operator precedence explicit.

A MISRA-C compliant version would be something like:

locvar = func();

if ((locvar == 1) || (locvar == 2)) {
  ...
}

CodePudding user response:

Further to @Lundin's answer, the only MISRA C:2012 consideration is if there is a persistent side-effect within func() - if there are no persistent side-effects then MISRA C has little to say.

Likewise from a code efficiency perspective, an efficient compiler will (probably) optimise the code - it may even inline the function body anyway...

For me, the primary consideration would be code readability (and hence maintainability) - a single call makes it clear what you are doing... and if there are no persistent side-effects what is to be gained from making a second function call?

I vote for Code 2.

CodePudding user response:

In theory, computing the value used in the branch condition can improve branch prediction for the processor, but an optimizing compiler should do this for you. In think this answer might be interesting:

conditional data transfers VS n conditional control transfers(using conditional mov) in Assembly

  •  Tags:  
  • Related