I am a beginner in C and I mostly used the following two formats of printf
#include <stdio.h>
//Compiler version gcc 6.3.0
int main()
{
int c=5;
printf("Hello, World!\n");
printf("%d",c);
return 0;
}
But recently I found out that there is one more way to write printf i.e. printf(string pointer), how this format is so different from the other two,there are no quotes and why there is string , the question can be a silly one but try to understand that I am just a beginner.
While it looks different in your editor, it's actually the same.
When you write
printf("Hello, World!\n");
in your editor, your compiler in principle change it to
char* hidden_unnamed_string = "Hello, World!\n";
printf(hidden_unnamed_string);
The string "Hello, World!\n" is called a string literal. The compiler will (automatically) place it somewhere in memory and then call printf
with that memory address.
Here is an example from godbolt.org
On the left side you have the C program as it looks in your editor. To the right you have the compiled program.
Notice how the string is located outside the code block and labeled with LC0. Then inside the code block LC0 is loaded into edi (i.e. the address of/pointer to the string is loaded into edi) just before calling the printing function.
Also notice that the compiler decided to use puts
instead of printf
. Further notice that the string is stored without the \n
. The reason is that puts
unlike printf
automatically adds a \n
.