9

Why does:

int test() {
    return 00101 % 10;
}

return 5, while:

int test() {
    return 101 % 10;
}

returns 1? I can't think of an explanation.

OJFord
  • 10,522
  • 8
  • 64
  • 98

3 Answers3

23

Integer literals beginning with 0 like

00101

is actually an octal constant.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 2
    This is the most confusing convention ever, it's totally contradictory to the way humans look at numbers. – Mark Ransom Sep 26 '14 at 17:31
  • Thanks a lot! Is there a way to work around this? I'm receiving values and I don't know how many leading zeroes there will be. – Kosmas Katsoulotos Sep 26 '14 at 17:33
  • 2
    @KosmasKatsoulotos How did you receive the values? You don't encounter this problem much other than dealing with literals. – Yu Hao Sep 26 '14 at 17:40
  • 2
    If you `fscanf` or whatever, `%d` in the format string will ignore/strip/interpret as decimal the leading zeroes. (`%o` is octal). – OJFord Sep 26 '14 at 18:29
5

00101 is octal value which is 65 in decimal so it returns 5.

Rustam
  • 6,485
  • 1
  • 25
  • 25
0

00101 is in octal which is equal to 65 in decimal, so that is why the modulus operator will always give us 5. You can do octal to decimal converstion on this link http://www.rapidtables.com/convert/number/octal-to-decimal.htm

Taimour
  • 459
  • 5
  • 21