-1
printf("%d", "10+10");

then I get "17661648" and similar thing in too

printf("%d", "Hello");

What is this value? sum of "1,0,+,1,0" "H,e,l,l,o" as ASCII code in decimal number? or just a garbage value?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Jang ES
  • 9
  • 3

2 Answers2

8

According the the C11 standard n1570 (see its §7.21.6.1) you've got undefined behavior (UB), which is also documented here or in printf(3). So be very scared, since arbitrarily bad things could happen. So take the habit of reading the documentation of every function that you are using.

If you ask your compiler to disassemble the generated form of your program (e.g. by compiling with gcc -S -O -fverbose-asm if you use GCC, on Linux/x86-64) you'll discover that the address of the string literal "10+10" is passed (on 64 bits) and then truncated (inside printf, because of the %d) to an int. So the 17661648 could correspond to the lowest 32 bits of that address.

Details are of course implementation specific (and could vary from one run to the next one because of ASLR, depends upon the compiler and the ABI and the target system). To actually understand and explain the behavior requires diving into many details (your particular computer, your particular compiler and optimization flags, your particular operating system, the compiler generated assembler & machine code, your particular C standard library, etc....) and you don't want to do that (because it could take years).

You should take several hours to read more about UB. It is an essential notion to understand when programming in C, and you should avoid it.

Any good compiler would have warned you, and then you should improve your code to get no warnings. If using GCC, be sure to compile with gcc -Wall -Wextra -g to get all warnings and debug info. Then use the gdb debugger to understand the actual behavior of your program on your system. In all cases, be sure to configure your C compiler to enable all warnings and debug info, and learn to use your debugger. Read How To Debug Small Programs.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • I'm a beginner of C and know not much about it. That's why I couldn't understand all of your comment but I think it is really helpful to me. Thank you for giving me a guide to study, I would try to as you tell. – Jang ES Jun 15 '18 at 04:59
  • You absolutely need to read more about UB. It is an essential concept in C programming, important even to beginners. And you should take the habit of compiling with all warnings and debug info. So read the documentation of your compiler and of your debugger. – Basile Starynkevitch Jun 15 '18 at 05:31
  • 1
    And any warning should be understood as an *error*. – Antti Haapala -- Слава Україні Jun 15 '18 at 06:03
-1

Someting like this should work:

printf("Hello");
total = 20;
printf("10+10 = %d", total);
Mike
  • 4,041
  • 6
  • 20
  • 37