1
votes

In the following code,

#include<conio.h>
clrscr();
gotoxy(10, 20);
ch= getch(a);

we can see that the library functions have been called without defining their prototype, the three library functions: clrscr() gotoxy(int int) and getch() have their prototypes defined in the conio.h header file which appear in the header file itself like this,

void clrscr();
void gotoxy(int int);
int getch();

But in the following code how does the compiler know the prototype of the printf() function? Since the code gets executed without any errors, although in the first printf() the last int format specifier prints the garbage value and in the second the value of j doesn't get printed at all since it has not been specified.

#include<stdio.h>
int i=10, int j=20;
printf("%d%d%d",i,j);
printf("%d",i,j);

How does the header file stdio.h describe the scenarios when the format specifiers are float or char variables for the printf() functions?

3
.... Note that good compilers will find the error anyway. - EOF
This is a thing called a variadic function. - Константин Ван

3 Answers

0
votes

The compiler knows the prototype because it's declared in <stdio.h>, which you're including.

<stdio.h> does not describe the format specifiers. It simply says

int printf(const char *, ...);

The ... indicates that printf takes a variable number of arguments (of unknown type).


Your first call to printf has undefined behavior (not enough arguments for the format string). Your second call is fine (excess arguments are simply ignored). C compilers are not required to detect format string issues like this.

0
votes

Any predefined function like printf should be prototyped or declared before using,in respective header file So that while executing the program compiler can verify whether programmer uses correct format or not.

printf() function prototype is declared in header file called stdio.h.

when compiler executes first line of your code which is #include<stdio.h> It came to know about printf prototype.

man 3 printf says

 int printf(const char *format, ...);// last 3 dots specifies the variable no of arguements printf can take 

In your code below printf is causing undefined behaviour because printf expects 3 arguments but you provided only 2 arguments.

printf("%d%d%d",i,j);
0
votes

The stdio header always includes the same declaration of printf() which is:

int printf(const char *fmt, ...);

the declaration is always the same no matter which placehoder you put into your format string.

Normally the definition\implementation of printf iterates over each character in the fmt string and will replace each identified placeholder with the appropriate argument. The compiled code will try to use the arguments instead of the placeholders in the same order as they are specified in the source code.