I mean without assigning its value into a variable, and using it.
For example:
int foo(void);
void main()
{
foo();
}
int foo()
{
return(5);
}
Why I can not get any warning
I mean without assigning its value into a variable, and using it.
For example:
int foo(void);
void main()
{
foo();
}
int foo()
{
return(5);
}
Why I can not get any warning
Many functions return a value and also perform side effects, but they're often used just for their side effects.
For instance, printf()
prints output and also returns the number of characters that were printed. But most of the time the return value is not interesting, so we don't assign it anywhere. fclose()
returns a success indicator, but there's usually nothing a program can do if it fails, so they don't bother checking the result.
It would be tedious to have to write things like:
(void)printf(...);
(void)fclose(f);
all the time, so compilers generally don't warn about calling non-void functions without using the result.
This can be a problem in some cases. There are some functions where you really should use the return value, but it's a common mistake not to use it. For instance, realloc()
returns the new pointer, but many beginners just assume that it will always resize the allocation that the old pointer points to.
Some IDEs probably have lists of functions that they should warn about for this reason. But compilers generally aren't as precise as that.
You are not obligated to store or examine a value returned from a function if you don't want to.
For example, printf
returns an int
representing the number of characters successfully written, but most of the time you just call printf
to produce output on the screen; you don't care about the return value. For example:
printf("Hello World!\n");
Is a lot more common than:
if(printf("Hello World!\n") != 13)
// printf failed
That said, there are a lot of static analysis tools that can enforce that code that calls certain functions must examine their return values. SAL, which I'm most familiar with, allows you to annotate a function with _Check_return_
or _Must_inspect_result_
, and if you then call a function annotated as such without checking its return value, analysis will report a warning.
Example:
#include <sal.h>
_Must_inspect_result_
int foo()
{
return 5;
}
int main(void)
{
foo();
return 0;
}
Running SAL analysis on this code produces the warning message:
C6031 Return value ignored: 'foo'.