Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 050 not equal to 50 in the following snippet?

Tags:

c

Why is 050 not equal to 50 in the following snippet?

#include <stdio.h>
int main(void) {
    int x=050,y=50;
    int ans;
    ans= x==y ? x+3 : y+7;
    printf("%d\n",ans);
}
like image 544
Babanna Duggani Avatar asked Oct 16 '11 06:10

Babanna Duggani


2 Answers

Because 050 is considered octal and 50 is considered decimal.

So x = 050 basically means x = 40.

6.4.4.1/3

A decimal constant begins with a nonzero digit and consists of a sequence of decimal digits. An octal constant consists of the prefix 0 optionally followed by a sequence of the digits 0 through 7 only.

like image 151
cnicutar Avatar answered Nov 08 '22 09:11

cnicutar


050 is interpreted as octal, with 8 instead of 10 as the number base.

like image 3
Anders Abel Avatar answered Nov 08 '22 09:11

Anders Abel