Print char using integer qualifier

I am trying to execute the program below.

#‎include‬ "stdio.h" #include "string.h" void main() { char c='\08'; printf("%d",c); } 

I get output as 56 . But for any numbers other than 8 , the output is the number itself, but for 8 answer is 56 .

Can someone explain?

+8
c ++
source share
4 answers

Characters starting with \0 represent Octal number , this is the base-8 number system and the digits 0 to 7 . Thus, \08 is an invalid octal representation, because 8 ∉ [0, 7] , so you get behavior defined by implementation.

Perhaps your compiler recognizes the Multibyte Character '\08' as '\0' one character and '8' as another and interprets it as '\08' as '\0' + '8' , making it '8' . Looking at the ASCII table, you will notice that the decimal value of '8' is 56.


Thanks to @DarkDust, @GrijeshChauhan and @EricPostpischil.

+18
source share

The value '\08' is considered a multi-character constant consisting of \0 (which evaluates to the number 0) and the ASCII 8 character (which evaluates to decimal 56). How this is interpreted is determined by the implementation. The C99 standard says:

An integer character constant is of type int. The value of an integer character constant containing one character that maps to a single-byte execution character is a numeric value representing the character being displayed, interpreted as an integer. The value of an integer character constant containing more than one character (for example, "ab") or containing a character or escape sequence that does not match a single-byte execution character is from the implementation . If an integer character constant contains a single character or an escape sequence, its value is the result when an object of type char whose value is a single character or the escape sequence is converted to int.

So, if you assigned '\08' to something bigger than char , like int or long , it would be valid. But since you assign it to char , you "chop off" some part. Which part is probably also implementation / machine dependent. In your case, this gives you a value of 8 (an ASCII character that evaluates to 56).

Both GCC and Clang warn of this problem with a "warning: multi-character character constant."

+7
source share

\0 used to represent octal numbers in C / C ++. Octal base numbers range from 0->7 , so \08 is a multi-character constant consisting of \0 , the compiler interprets \08 as \0 + 8 , making it '8' , whose ascii value is 56 . That is why you get 56 as output.

+4
source share

As the other answers said, these numbers represent octal characters (base 8). This means that you need to write '\010' for 8, '\011' for 9, etc.

There are other ways to write an appointment:

 char c = 8; char c = '\x8'; // hexadecimal (base 16) numbers 
+4
source share

All Articles