سؤال

What does the following code 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top