0

I am not getting why this is happening ?

int a = 012;        
int b = 12;

if (a == b) {
    NSLog(@"equal");
}else
    NSLog(@"not equal");

why it is printing not equal ?

Larme
  • 24,190
  • 6
  • 51
  • 81
sanjeet
  • 1,539
  • 15
  • 37

2 Answers2

4

Okay. This is because the C int type interprets literals with leading zeros as octal.

To demonstrate this, adapt your example to the following:

int a = 012;
int b = 12;
if (a == b) {
    NSLog(@"%d does equal %d", a, b);
} else {
    NSLog(@"%d does NOT equal %d", a, b);
}

Outputs:

10 does NOT equal 12

That is because in octal (1 * 8 = 8) + 2 = 10

Further information can be found at: https://en.wikipedia.org/wiki/Integer_literal#Affixes

R. Hatherall
  • 1,121
  • 14
  • 11
1

Leading zeros indicate that the number is expressed in octal, or base 8; thus, 012 is converted into octal as (1*8)+2 = 10. Because of this reason the if statement returning false.

int a = 012;
int b = 12;

NSLog(@"%d", a);
NSLog(@"%d", b);

if (a == b) {
    NSLog(@"equal");
}else {
    NSLog(@"not equal");
}

Output: not equal.

Ramesh_T
  • 1,251
  • 8
  • 19