Search code examples
cfflush

fflush(stdin) ANSI C


I am a beginner in ANSI C, and I have a question, it may be silly question and I am sorry for it.

#include<stdio.h>
    main()
    {
          int age;
          printf("Hello World!\n");
          printf("Please enter your age: ");
          scanf("%d", &age);
          printf("You entered %d\n", age);
          fflush(stdin);
          getchar();
    }

It is my second program to learn scanf function. My question is : I know that printf, scanf, fflush, stdin, and getchar are defined in stdio.h but only when I use fflush(stdin) I must put #include<stdio.h>, but when use any other method I can remove that line #include.


Solution

  • You must have #include <stdio.h> when you call any function declared in that header.

    Ok, that's not quite true. In the 1989/1990 version of the language standard, a call can create an implicit declaration of a function. If that happens to match the correct declaration, you can get away with it;. Otherwise your program's behavior is undefined -- which means you still might get away with it, or not, but the compiler isn't required to warn you about it. Since printf takes a variable number of arguments, you must have a visible declaration to avoid undefined behavior -- and the way to get a visible declaration is #include <stdio.h>.

    (You can also declare the function yourself, but that's error-prone, and there's no good reason to do that.)

    In C99 and later, there are no implicit declarations.

    main() should be int main(void).

    fflush(stdin) has undefined behavior. If you want to discard characters entered after the scanf() call, you can read and discard them.