2

Output of this code is 56.

// Output : 56

#include <stdio.h>

int main() {
    char c = '\08';
    printf("%d",c);
    return 0;
}

3 Answers3

7

As @stark commented, Your constant consists of 2 bytes '\0' and '8'. These are truncated to '8' when stored in the variable c.

In ASCII Character Chart you can see that 8 is 56 in ASCII, and you get that because you use the %d format specifier to print:

enter image description here

You could have seen that yourself, if you paid attention to your warnings:

main.c:4:14: warning: multi-character character constant [-Wmultichar]
    4 |     char c = '\08';
      | 

Moreover, I suggest you try printing like this:

printf("%c", c);

and then the output would be:

8

which shows you what was really stored in the variable c.


Tip: If you use char c = '\01'; or char c = '\07'; and anything in between, you will see no warning and the corresponding number being printed, because these are valid octal digits, as @Gerhardh's answer mentions.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 1
    But when i change 8 with other no less than eight it simply print the same no. not its ASCII value for example : c = '\01' prints 1 instead of 49 – Shivam Tyagi Nov 09 '19 at 12:02
  • @ShivamTyagi please see my anser. Digits below 8 are valid octal digits and extend the escaped value. The first character that is no valid octal digit is treated as the next separate character. – Gerhardh Nov 09 '19 at 12:04
  • @ShivamTyagi if you use anything in between `\01` and `\07`, you will see *no warning*, because there are **valid octal digits**. See my updater answer for more, or simply check Gerhardh's. :) – gsamaras Nov 09 '19 at 12:05
  • 1
    thanks now i understand how this works :) – Shivam Tyagi Nov 09 '19 at 12:07
4

In C strings or character literals, it is possible to escape hexadecimal or octal values.

the prefix '\0' is used for octal values, while '\x' is used for hex values. This means '\0' is equal to value 0, '\011' is equal to 9 etc.

In your case a '8' follows which is no valid octal digit. Therefore the escape sequence stops there and your literal is same as value 0 followed by character '8'.

Now you have a character literal with more than 1 character. This is a multibyte character literal and the value of this literal is implementation dependend. In your case the final value of the character is the value of the last character, e.g. '8' which has ascii value 0x38 or 56.

As you print this as a decimal number, you get 56.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
0

Its taking value of '8' as char. In ASCII its 56. Basicly char holds only 1 character

Maqcel
  • 493
  • 5
  • 16