0

I am not able to understand the behavior of multi-character literal assignments. For instance take below program:

#include <stdio.h>

int main(void) {
    // your code goes here
    char a = '\010';
    int b = 010;
    char c = '310';
    char d = '\310';
    int e = 0310;
    int f = 0x10;
    char g = '\0x10';
    char h = 'A';
    char i = 'hello';
    char j = '\hello';
    char k = '\0hello';
    printf("a=%d b=%d c=%d d=%d e=%d f=%d g=%d h=%d i=%d j=%d k=%d", a, b,c, d, e, f, g, h, i, j, k);
    return 0;
}

This outputs:

a=8 b=8 c=48 d=-56 e=200 f=16 g=48 h=65 i=111 j=111 k=111

How are we getting these values? They do not look like ASCII values. How does multi-character literal work in C? What is the significance of \ if any?

CodeTalker
  • 1,683
  • 2
  • 21
  • 31
  • 1
    Does this answer your question? [What do single quotes do in C++ when used on multiple characters?](https://stackoverflow.com/questions/7459939/what-do-single-quotes-do-in-c-when-used-on-multiple-characters) – ShadowRanger Nov 21 '22 at 17:32
  • Also related/informative: [Multicharacter literal in C and C++](https://stackoverflow.com/q/3960954/364696), [Octal representation inside a string in C](https://stackoverflow.com/q/11815076/364696) and [Rules for C++ string literals escape character](https://stackoverflow.com/q/10220401/364696) – ShadowRanger Nov 21 '22 at 17:33
  • 1
    Short version: `\ooo` (where up to three octal digits follow the backslash) is an octal escape representing a single character. Virtually everything else you did is a multicharacter literal, which is allowed, but stores the data in a purely *implementation-defined* (read: **non-portable**) way. It's extremely rare for multicharacter literals to be useful; the main case is being able to define `enum`s which can be `switch`ed on (converting inpts to the `enum` would require preprocessor checks to define macros/functions to ensure the conversion matches the order the literals produce). – ShadowRanger Nov 21 '22 at 17:38
  • 3
    Start by enabling compiler warnings and treat warnings as errors. That will eliminate a few of your options that we don't need to explain. – Cheatah Nov 21 '22 at 17:41
  • @CodeTalker `010` is an `int` constant written using _octal_ digits. What value do you expect? – chux - Reinstate Monica Nov 21 '22 at 20:39

0 Answers0