开发者

What does the following code fragment (in C) print?

What does the following co开发者_运维技巧de fragment (in C) print?

int a = 033;
printf("%d", a + 1);


033 is an octal integer literal and its value is 8*3+3 = 27. Your code prints 28.

An integer literal that starts with a 0 is octal. If it starts in 0x it's hexadecimal.

By the way, for an example's sake

int x = 08; //error

is a compile-time error since 8 is not an octal digit.


I would risk a wild guess and say 28 :)


28.

033 is an octal number in C because it has a leading "0" and that means its value is 27 in decimal.

So, 27 + 1 = 28


here's a cue:

  • a 3-digit with zero in the beginning is an octal.
  • a 2-digit value with "0x" in the beginning is a hex.

Try looking at this example:

 #include<stdio.h>
 main()
 {
 int a = 033;
 printf("\nin decimal: %d", a+1);
 printf("\nin hex: %x", a+1);
 printf("\nin octal: %o", a+1);
 }

this results in:

in decimal: 28
in hex: 1c
in octal: 34
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜