Scanf statement

2019-08-27 19:06发布

问题:

#include <stdio.h>
#include <stdlib.h>

Hello, I was wondering why this program doesn't execute. It seems as though I've always been having trouble with performing the scanf function properly. I get the error of:

error: ignoring return value of scanf declared with attribute warn_unused_result

Note: I know there is a more efficient method for writing my current program, but that is beside the point. I want to know what this error means and why I keep getting it and possibly a solution. Thank you guys. Here is the code:

int main (int argc, char *argv[]){

    int x;
    int y;
    int z;
    int temp;

    scanf("%d", &x);
    scanf("%d", &y);
    scanf("%d", &z);

        if (x > y) {
           temp = x;
           x = y;
           y = temp;
        }

        if (y > z) {
            temp = y;
            y = z;
            z = temp;
        }

        if (x > z) {
            temp = x;
            x = z;
            z = temp;
        }

        printf("%d", x);
        printf("%d", y);
        printf("%d", z);

  return EXIT_SUCCESS; }

回答1:

The error that you get from the compilers is just what it says. In order for your application to be correct, you have to check the return value of scanf. The possible return values are described in the man page.

For an explanation of what causes the error, see the "warn_unused_result" part of gcc manual (quoted in Peter R.s reply).



回答2:

From the GCC documentation:

The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug, such as realloc.

      int fn () __attribute__ ((warn_unused_result));
      int foo ()
      {
        if (fn () < 0) return -1;
        fn ();
        return 0;
      }

results in warning on line 5.



标签: c scanf