Mattmmmmm
Mattmmmmm

Reputation: 189

The usage of a backslash character(\) in an char assignment expression

char C = '\1'
int I = -3
printf("%d", I * C);

output:

-3

Hi, I just saw this weird syntax in my practice book, but it doesn't give me much detail about what it is and its usage. Why is there a backslash next to 1 in the quotation mark? Is '\1' any different from '1'? If so, why the result of I * C is the same as 1 * 3? Thank you

Upvotes: 0

Views: 1335

Answers (3)

KamilCuk
KamilCuk

Reputation: 141940

The '1' is the character “1”. Most platforms nowadays use ASCII to translate characters into bytes — '1' in ASCII is an integer 49 in decimal or 0x31 in hex.

From cppreference escape sequence:

\nnn  arbitrary octal value   byte nnn

Octal escape sequences have a limit of three octal digits, but terminate at the first character that is not a valid octal digit if encountered sooner.

The '\1' is an integer 0x1 in hex or 1 in decimal. In ASCII, it is a SOH character — start of heading.

The:

char C = '\1';

is equivalent to:

char C = 1;

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

In the initializer of the variable C

char C = '\1';

there is used an octal escape sequence. That is the digits after the backslash are considered as an octal representation of a number.

The number of digits in the octal escape sequence shall not be greater than 3 and the allowed digits are 0-7 inclusively.

For example this declaration

char C = '\11';

initializes the variable C with the value 9.

So the expression used in the call of printf

printf("%d", I * C);

is equivalent to

printf("%d", -3 * 1);

And the output will be -3.

Instead of the octal escape sequence you could use hexadecimal escape sequence like

char C = '\x1';

this declaration is equivalent to the previous declaration of the variable C like

char C = '\1';

If to initialize the variable like

char C = '\x11';

then the variable C will get the value 17.

The number of digits in the octal escape sequence shall not be greater than 3 and the allowed digits are 0-7 inclusively.

As for a declaration like this

char C = '1';

then the variable C is initialized by the value of the internal representation of the character '1'. For example if the ASCII coding is used the variable C is initialized by the value 49. If the EBCDIC coding is used then the variable C is initialized by the value 241.

Upvotes: 2

dlask
dlask

Reputation: 9002

'1' is internally a byte whose value is 49 (the ASCII code of symbol 1).
'\1' is a byte whose value is 1.

Upvotes: 0

Related Questions