开发者

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

开发者 https://www.devze.com 2023-01-29 01:48 出处:网络
What does the following co开发者_运维技巧de fragment (in C) print? int a = 033; printf(\"%d\", a + 1);

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

精彩评论

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