Click here to Skip to main content
15,915,080 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Why I am not getting error even though I am not not passing any format specifier but passing a string literal. There is no error in the case of string literal but there is an error in the case of character,integer. Why ?

What I have tried:

#include<stdio.h>
int main()
{
printf("Hello World");
return 0;
}
Posted
Updated 23-Apr-21 14:51pm

The documentation on printf is as follows:
C
int printf ( const char * format, ... );

Print formatted data to stdout
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.

format
A C string that contains the text to be written to stdout.
It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.

...

In your case of putting a char or int variable in place of format above will fail because, well, they are not strings.
 
Share this answer
 
In this case it prints "Hello World". In fact, if I recall correctly, that's the first program in K&R. Its quite normal for a C program to use printf to print a string to stdout. So common, in fact that gcc will replace the call to printf that ends in a newline, and has no formatting tokens with a call to puts(), when opimizations are enables.

Now, if it was
C
#include <stdio>

int main()
{
    printf("Hello World %s\n");
    return 0;
}
there's a problem ... We've told printf() to expect a string to print, but not given it one. printf will happily take the next item up the stack and attempt to use that as an address as a null terminated C string. So it might print "Hello World aCR433z++!azre...", or it might crash your computer.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900