Can anyone please explain the below code and please also explain the role of backslash( \
) in such situations. And what \'
, \"
, \ooo
, \ \
, \?
means?
#include <stdio.h>
int main(){
char a = '\010';
char y = '010';
printf("%d,%d",a,y);
return 0;
}
output: 8,48
In the first case,
\010
is interpreted as an octal which results in8
.In the second case, the ascii value of
0
(the first character in010
) is returned, which is48
.If you had compiler warnings on, chances are that you'd have figured the second one
by yourself. (
gcc
would have emitted-Wmultichar
and-Woverflow
in this case.)Quoting C1X draft, section 6.4.4.4:
Hope this helps:
Escape sequences are character combinations that comprise a backslash (\) followed by some character. When you're programming in almost all languages, sometimes you need to refer to a key press that doesn't result in a specific character.
For e.g. suppose you develop a language that assumes a variable to be enclosed with Box brackets
[var]
- then if you are inputting a value other than a variable then you will have to escape it like\[10\]
. Otherwise your compiler will think that10
is a variable name.It is an escape sequence to remove meaning of some reserved character such as
'
or to specify some special character such as new-line'\n'
or in this case a character with specific ASCII value:defines a character with octal ASCII value 108, i.e. decimal value 810.
defines a multi-byte character, which should be assigned to wide char, not
char
. Although the behavior of this assignment is not defined, in this case it will most likely cause the last character being stored, iny
This
'\010'
is a octal escape sequence10
in octal is8
in decimal and it will be promoted to anint
when callingprintf
so that explains that value.This
'010'
is a multi-character constant and it's value is implementation defined, if we look at the C99 draft standard section6.4.4.4
Character constants paragraph 10 says(emphasis mine):and if you were using
gcc
you would have seen at least this warning:and probably this warning as well on overflow:
the value that
y
obtains is a little more interesting since character constant has an integer value it can not just be taking the first character, the multi-character constant has to take an integer value and then be converted to char.clang
helpfully provides a more detailed warning:and current versions of
gcc
produces the same value, as we can see from this simple piece of code:so where does
3158320
comes from? Forgcc
at least, if we look at the documentation for Implementation-defined behavior it says:if we perform the operation(assuming 8-bit char) document above we see:
gcc
will convert theint
tochar
using modulus2^8
regardless of whetherchar
is signed or unsigned which effectively leaves us with the last8
bits or48
.It is an escape sequence - see http://en.wikipedia.org/wiki/Escape_sequences_in_C