Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: ignoring return value of 'scanf', declared with attribute warn_unused_result

Tags:

c

#include <stdio.h>  int main() {     int t;     scanf("%d", &t);     printf("%d", t);     return 0; } 

I compiled the above C code using ideone.com and the following warning popped up:

prog.c: In function ‘main’:
prog.c:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result

Can someone help me understand this warning?

like image 734
vipin Avatar asked Sep 01 '11 14:09

vipin


People also ask

Why is return value ignored scanf?

You don't capture the return value of scanf in a variable. It's a count (as an integer) of how many characters were read, so if that's important to you, then it may be good to capture it. And it is important to you, believe me. But it's a count of how many items were successfully scanned, not characters.


2 Answers

The writer's of your libc have decided that the return value of scanf should not be ignored in most cases, so they have given it an attribute telling the compiler to give you a warning.

If the return value is truly not needed, then you are fine. However, it is usually best to check it to make sure you actually successfully read what you think you did.

In your case, the code could be written like this to avoid the warning (and some input errors):

#include <stdio.h>  int main() {     int t;     if (scanf("%d", &t) == 1) {         printf("%d", t);     } else {         printf("Failed to read integer.\n");     }     return 0; } 
like image 104
Evan Teran Avatar answered Oct 05 '22 16:10

Evan Teran


The warning (rightly) indicates that it is a bad idea not to check the return value of scanf. The function scanf has been explicitly declared (via a gcc function attribute) to trigger this warning if you discard its return value.

If you really want to forget about this return value, while keeping the compiler (and your conscience) happy, you can cast the return value to void:

(void)scanf("%d",&t); 
like image 31
Alexandre C. Avatar answered Oct 05 '22 15:10

Alexandre C.