开发者

Size of escaped characters in C

开发者 https://www.devze.com 2023-02-14 15:48 出处:网络
Why does the following program output 5? #include <stdio.h> main() { char str[]=\"S\\开发者_Python百科065AB\";

Why does the following program output 5?

#include <stdio.h> 
main() 
{ 
    char str[]="S\开发者_Python百科065AB"; 
    printf("\n%d", sizeof(str)); 
}


Short answer: See David Heffernan's answer.

Long answer:

§ 6.4.4.4 of the C(99) standard specifies "character constants", which (among others) include simple escape sequences (e.g. '\n', '\\'), octal escape sequences (e.g. '\0'), hexadecimal escape sequences (e.g. '\x0f'), and universal character names (e.g. '\u0112').

The backslash in your example introduces such an escape / octal / hex / universal constant. The following octal digit ([0-7]) makes it an octal constant (hex would be '\x', universal would be '\u', escape sequence would be '\['"?\abfnrtv]').

That octal constant is terminated once three octal digits are consumed, or a non-octal-digit is encountered.

I.e., '\065' is equivalent to '\x35' or (decimal) 53, which is (coincidentally) '5' on the ASCII table - a single character, anyway.


It's the size of the array which has five elements: S, \065, A, B, \0

0

精彩评论

暂无评论...
验证码 换一张
取 消