问题描述:

line_c=0;

line_c |= 064; /* wrongly sets bits 2,4 and 5 */

line_c |= 64; /* rightly sets bit 6 */

Misra C guideline. How does this happen? Please explain.

网友答案:
line_c |= 064; /* wrongly sets bits 2,4 and 5 */

-> 064 (leading zero) means octal 64 (base 8), which is 0011 0100 binary.

line_c |= 64; /* rightly sets bit 6 */

-> decimal 64 (base 10), converts to 0100 0000 binary.

网友答案:

An integer literal with leading 0 is an octal number. So 064 is not 64 (base 10). 064 is 52 in decimal. Hence, it sets different bits to what 64 sets.

网友答案:

In C, there are decimal, octal and hexadecimal literals.

The hexadecimal ones are easily recognizable, because they start with 0x, like 0xff for the decimal number 255.

The octal ones are those that start with the digit 0, possibly followed by further digits 0..7. Therefore, the literal constant 0 is in fact syntactically an octal constant. That is the reason why MISRA rule 7.1 is formulated in the following way: "Octal constants (other than zero) and octal escape sequences shall not be used." Since 0 is an octal constant, they explicitly have to allow its use :-)

Decimal constants, finally, are those that start with a digit 1..9, and then possibly further digits 0..9. That's the reason 064 is different from 64.

相关阅读:
Top