MISRA C - Rule 12.12

6.12 Expressions

Moderators: misra-c, david ward

Post Reply
Posts: 4
Joined: Mon Aug 12, 2013 10:12 am
Company: TCS

MISRA C - Rule 12.12

Post by Akhil » Wed Sep 18, 2013 8:00 am

Just wanted to know if Line 3 in the following case is a violation for Rule 12.12 ...??

1. int i;
2. float f=2.1;
3. i=(int)f >>2; //Typecasting should actually take care of the bit implementation of floats

Also, If its a violation to Rule 12.12..Does that mean all typecasts (from float to any other type) should also be considered as violationg this rule..?

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

Re: MISRA C - Rule 12.12

Post by Steve Montgomery » Tue Oct 01, 2013 1:15 pm

In my opinion, Rule 12.12 intends to prevent direct access to the representation of floating-point values. This might typically be achieved using either a union or pointer casts, for example:

Code: Select all

unsigned int tmp = *(unsigned int *)&f; /* get the float as 32-bit int */
tmp = tmp ^ 0x80000000;  /* flip the sign bit */
f = *(float *)&tmp;  /* store the result back */
I don't think that casting a floating-point value to int violates Rule 12.12 because there is no direct access to the representation of the value. In addition, the conversion is well-defined in that the floating point value is truncated towards zero with the result being undefined only if the truncated value won't fit in the integer type.

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

Re: MISRA C - Rule 12.12

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

This example does not violate rule 12.12 as there is no access to the underlying floating representation as discussed by Steve in a previous post.
Posted by and on behalf of
the MISRA C Working Group

Post Reply

Return to “6.12 Expressions”