Funny Division in C and Arduino

Viewed 113

TL;DR Why does

   printf("%d\n", 042/10  );

return 3 and not 4?

Hey so i actually i actually had this doubt while i was in the Arduino IDE, but then just to verify I did try in another C compiler. The code in Question is here:

Serial.println(42/10);

This works fine, displays 4. The is the funny bit

Serial.println(042/10);

This return 3.

This seems very fundamental but I couldn't find a suitable post answering this. Thanks in Advance!

3 Answers

The leading zero means it’s octal. 042 is equal to 34 in decimal. And 34/10 is indeed 3 using int math.

The 042 from printf("%d\n", 042/10 ); is interpreted as an octal value:

042 (oct) = 34 (dec)

so your division is actually: (int)34/10 = 3

Serial.println(042/010); will output 4

Stems from the earliest days of C, when octal numbers were at least a bit more common than nowadays (?). Once it's defined, you can't ever change it.

Related