Home > Back-end >  what is that value got printed when I tried to print the string with %d? [duplicate]
what is that value got printed when I tried to print the string with %d? [duplicate]

Time:09-21

#include <stdio.h>

int main()
{
    printf("%d\n","Zara Ali"); // integer 
    printf("%s","Zara Ali"); // string
    return 0;
}

this is the code

and the output is

4195828
Zara Ali

plz somebody explain it.

CodePudding user response:

printf("%d\n","Zara Ali");

This code has undefined behavior because the type of the argument (char*) isn't the type that's required for the %d format specifier (int).

"Undefined behavior" means that the C standard imposes no requirements on what will happen. The program could fail to compile, it could crash at run time, it could print random garbage that isn't necessarily and integer value, or literally anything else.

The most likely result is that the call will pass the address of the character string to printf, which will interpret that address as an int value. If int and char* happen to have the same size, you might get a meaningful representation of that memory address. (Use printf("%p\n", (void*)"Zara Ali"); if you want to see a meaningful, but implementation-defined, representation of that address.)

It's also possible, but I think not typical, that integer and pointer arguments might be passed in different registers, so the garbage value printed by printf might be unrelated to anything.

Bottom line: The code is incorrect, and it needs to be fixed. If your goal is to create a working program, don't waste your time trying to figure out why it behaves the way it does.

If you're curious about the inner workings of the implementation you're using, exploring the behavior of code like this can be illuminating, but don't expect it to behave consistently.

CodePudding user response:

Technically, the value printed is the memory location of the literal string "Zara Ali" (i.e. the memory location of the character 'Z' in your case).

As far as intent goes: it probably is not very useful to print the memory location of the string (as the comments to your post highlight).

  • Related