3

Following the logic from this question, the following code should work:

#include <stdio.h>

int main(){
    printf("%c", '\0101');
    return 0;
}

However, it gives the following error:

main.c: In function 'main':
main.c:5:18: warning: multi-character character constant [-Wmultichar]
     printf("%c", '\0101');
                  ^~~~~~~
exit status -1

I am not sure why it is a multi-character constant. I believe there should only be a single character constant inside those single quotes (octal 101 = decimal 65 = 'A'). Why are there more than one characters? And why isn't octal notation not working?

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
  • 3
    I'm no C expert, but octal character literals are 3-digits, aren't they? You don't specify the initial 0, that's just for numeric literals I think. – Lasse V. Karlsen Jun 22 '18 at 14:38
  • `'\0101'` -> `'\101'` – Jabberwocky Jun 22 '18 at 14:39
  • 1
    Why the error is talking about `"%s"` while the code has `"%c"`? – Eugene Sh. Jun 22 '18 at 14:45
  • 1
    @LasseVågsætherKarlsen For character literals leading zero is not needed. It is needed for integer octal literals. See https://en.cppreference.com/w/cpp/language/escape ... update ah.. it's for C++.. but same idea – Eugene Sh. Jun 22 '18 at 14:46
  • @EugeneSh. Sorry, I copied the wrong code, that `%s` is a typo. Although if you run the `repl` file I linked to, it gives the same error I was talking about. Also, it seems that the cppreference link is the answer I needed. Could you please post an answer? Thanks! – Gaurang Tandon Jun 22 '18 at 14:51
  • 1
    when writing an OCTAL character, use a leading 0 but do NOT use a leading '\' – user3629249 Jun 23 '18 at 15:40

2 Answers2

7

The octal char notation ought to be of the form \abc where a, b, and c, are octal digits (i.e. in the inclusive range of 0 to 7).

Your has four digits, so the compiler will interpret it as \010 (maximal munch) followed by 1.

That's a multicharacter constant, rather like '12'. Like \abc, that has an int type but the value is implementation defined, and the conversion to c in printf will have implementation-defined behaviour. Your helpful compiler is alerting you of that and, not surprisingly, is using correct terminology.

Did you mean to write '\101'? If you did, and what you really wanted was the upper case letter A, then write 'A' for portable C.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
6

It should be '\101' not '\0101'. You can use '\x41'(Hexadecimal) or '\101'(octal) instead of 'A'. But both reduces the portability and readability of your code. You should only consider using escape sequences when there isn't a better way to represent the character.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
anoopknr
  • 3,177
  • 2
  • 23
  • 33