Monday 15 April 2013

memory - Please explain this result please. printf("%c", 'abcd') -



memory - Please explain this result please. printf("%c", 'abcd') -

#include <stdio.h> int main() { printf("%c\n", 'abcd'); printf("%p\n", 'abcd'); printf("%c\n", 0x61626364); printf("%c\n", 0x61626363); printf("%c\n", 0x61626365); homecoming 0; }

i want inquire line : printf("%c\n", 'abcd'); in line, result 'd' but, can't understand why 'd' come out. tried other memories. in situation, found other memories have alphabets. please explain me why result 'd' , why other memories have alphabets. give thanks you.

your code wrong. when compile recent gcc compiler enabling warnings with

gcc -wall -wextra u.c

you get

u.c: in function 'main': u.c:5:20: warning: multi-character character constant [-wmultichar] printf("%c\n", 'abcd'); ^ u.c:6:20: warning: multi-character character constant [-wmultichar] printf("%p\n", 'abcd'); ^ u.c:6:5: warning: format '%p' expects argument of type 'void *', argument 2 has type 'int' [-wformat=] printf("%p\n", 'abcd'); ^

technically, in awful undefined behavior case (and unspecified behavior multi-character constants), , anything happen standard compliant implementation.

i never saw useful case multi-character constants 'abcd'. believe useless , historical artefact.

to explain happens, implementation specific (depends upon compiler, processor, optimization flags, abi, runtime environment, ....) , need dive gory details (first @ generated assembler code gcc -fverbose-asm -s) , libc particular printf implementation.

as rule of thumb, should improve code rid of every warnings compiler able give (your compiler helpful in warning you). few subtle exceptions (but should comment code them).

c memory character-encoding printf

No comments:

Post a Comment