Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda