Rule 12.4 - Do not use expressions with side effects

6.12 Expressions

Moderators: misra-c, david ward

Post Reply
jbrookley
Posts: 12
Joined: Thu Aug 08, 2013 5:56 pm
Company: Kavlico

Rule 12.4 - Do not use expressions with side effects

Post by jbrookley » Thu Oct 24, 2013 11:17 pm

Hello everyone,

I am having a problem with rule 12.4 (Do not use expressions with side effects in the right hand operand of a logical '&&' operator). My code is as follows:

Code: Select all

if ((DualDAC == 0) && (ADC1Flag <= 0u))
{
// Code Here
}
DualDAC is a bit, ADC1Flag is an unsigned char.

Is there a MISRA compliant way of writing this apart from a nested if loop? (as shown below):

Code: Select all

if (DualDAC == 0)
{
     if(ADC1Flag <= 0u)
     {
          // Code Here
     }
}
Any help you can give me would be greatly appreciated. Thanks!

Steve Montgomery
Posts: 104
Joined: Fri Sep 17, 2004 1:31 pm
Company: .
Location: Northumberland or Isle of Skye

Re: Rule 12.4 - Do not use expressions with side effects

Post by Steve Montgomery » Fri Oct 25, 2013 8:33 am

I'm assuming that ADC1Flag has a volatile qualified type so that the act of reading its value it is a side-effect. That being the case, I think you have only two options: either nest the tests (as you did in your proposed solution), or perform the volatile access first, e.g.

Code: Select all

flag = ADC1Flag <= 0u;
if ((DualDAC == 0) && flag)
{
// Code Here
}
The functional difference between the two methods is that the first one only accesses ADC1Flag if the (DualDAC == 0) condition is satisfied, whereas the second accesses it regardless. Since accessing a volatile has potential side-effects, such as unlatching data, clearing status flags and so on, which of the options is the right one depends on you application and the hardware you are running on. That's why the rule is there: to remind you that the RHS of a logical operator isn't always evaluated and to force you to make explicit in your code whether you want that behaviour or not.

In passing, I'd note that it's unusual, though not incorrect, to test an unsigned quantity against 0 using a <= operator. An unsigned quantity can never be less than zero so it's more usual to use == in this situation.

jbrookley
Posts: 12
Joined: Thu Aug 08, 2013 5:56 pm
Company: Kavlico

Re: Rule 12.4 - Do not use expressions with side effects

Post by jbrookley » Mon Oct 28, 2013 10:20 pm

So glad I posted here, I didn't understand WHY this was happening. While it's kind of a bummer to need a nested if loop, codewise, apparently, it's the same size so it's not a huge deal. Thanks for your help!

misra-c
Posts: 572
Joined: Thu Jan 05, 2006 1:11 pm

Re: Rule 12.4 - Do not use expressions with side effects

Post by misra-c » Fri Dec 13, 2013 9:04 am

We feel that Steve has given a good response to this question and have nothing more to add.
---
Posted by and on behalf of
the MISRA C Working Group

Post Reply

Return to “6.12 Expressions”