I want to know how the scanf function is implemented. (Just for fun, of course) The number of arguments is variable, so it is certainly implemented by the macros va_list , va_arg .
It also issues some warnings when the number of arguments does not match the format string. This can be done by parsing the format string and comparing it with the number of arguments. No magic.
The only thing I do not see how this is implemented is type checking. When the type of the argument (data pointer) does not match the corresponding declaration in the format literature, scanf issues a warning. How to check the type of data the pointer points to?
Example:
#include<stdio.h> int main() { char buffer1[32], buffer2[32]; int n; double x; scanf("%s %s %d",buffer1, buffer2, &x); // warning scanf("%s %s %d",buffer1, buffer2, &n); // ok }
Output:
warning: format '%d' expects argument of type 'int *', but argument 4 has type 'double *' [-Wformat]
AFAIK C-library is not part of the C / Compiler language, so there is no language binding in <stdio.h> . I assume that the warning is generated by implementing scanf , and not by the compiler [?]. (Perhaps using #warning )
If I want to do something similar in some code, how do I know which data type the pointer points to?
Note I downloaded the source code of the GNU C library and looked at scanf.c . I cannot find my way through very complex code. There is a lot of #ifndef and calls other functions with strange names and structure ...
source share