Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

293
Views
Which form is better for return value of functions in embedded C?

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 */    
}
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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)) {
  ...
}
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!