#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?
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.
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; }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With