Need for prefixing a function with (void) - c

I recently came across a rather unusual coding convention wherein the call for a function returning "void" is prefixed with (void).
e.g.
(void) MyFunction();
Is it any different from the function call like:
MyFunction();
Has it got any advantage or is it yet another needless but there coding convention of some sort?

Some functions like printf() return a value that is almost never used in real code (in the case of printf, the number of characters printed). However, some tools, like lint, expect that if a function returns a value it must be used, and will complain unless you write something like:
int n = printf( "hello" );
using the void cast:
(void) printf( "hello" );
is a way of telling such tools you really don't want to use the return value, thus keeping them quiet. If you don't use such tools, you don't need to bother, and in any case most tools allow you to configure them to ignore return values from specific functions.

No, there isn't any difference -- what's being cast to void is the return value of the function.
I'd say it could make sense of you wanted to make explicit you're not using the return value (you're calling it for the side effects), but as the function already has void return, it doesn't make much sense.

If the function returns something the void could avoid (!) a warning (indeed in no way I was able to make gcc warn me that the return value is lost) on some compilers (or lint tools); but more importantly, it makes clear that a return value is "thrown" away purposely (and not by mistake).

acedemically: a "function" always returns something, else it would be a procedure. So the Author of this code wants to say "i know this naming is wrong, but i will no change the name, so i make this disturbance visible"

Has it got any advantage or is it yet another needless but there coding convention of some sort?
No difference. It is a quite common convention e.g. in software testing to highlight the fact that in context the function return, if any, is safe to be discarded.

In HPUX man pages it is quite common in example code to see a cast to void to get around lint warnings.
fprintf(mystream, "%s\n", "foo");
vs.
(void)fprintf(mystream, "%s\n", "foo");
That may be where the author of the code is coming from. IMO, this is not a great idea because most of the sprintf family, for example, call malloc. malloc will fail when there is not enough memory. SIGINT also causes the underlying write() syscall to interrupt and not write all of the buffer, for printf() family members.

Related

Why does C let you ignore returned values from functions?

Let's say I have the following C code:
int return_one()
{
return 1;
}
int main(void)
{
return_one();
}
Within the main function, I call function return_one() and ignore the return value. The compiler has no issue with me ignoring this value.
What is the logic as to why this okay? Was it an arbitrary design choice from the C creators? Or is there a practical reason for not requiring the calling function to use the return value?
I think the main reason is the usual one — history.
Before the C standard, there was no option to use void to indicate 'no return value'. Functions returned an int unless you specified that they returned some other type, but that other type couldn't be void (it didn't exist). So functions for which the return value was immaterial didn't return a value — even though the function was implicitly returning type int. (Usually, the return type was omitted — the function was implicitly returning an int.) You got UB if the calling code tried to use a value but the called function didn't return a value.
All this meant that it was commonplace to ignore the return value of functions — especially functions that nominally returned an int but actually didn't return any value. There wasn't a better way of dealing with it. Nowadays, with void return types, there are better ways to deal with it. Nevertheless, it remains true that the return value is often of limited interest. How often do you check the return value of printf() or one of its friends? How often do you use the return value of strcpy() et al?
C90 had to allow old code to run still, so it allowed the old, pre-standard behaviour. C99 tightened the rules — functions were no longer implicitly of type int and had to be declared (with an explicit return type, possibly void) before they could be used.
Because people don't care about a lot of return values, so why force them to use them?
A ton of standard C functions return values that are essentially never looked at. Think about all the C code you've ever looked at. Have you ever seen someone do anything with the return value from the printf family of functions? Because they all have one, but you'd never know it to look at real world code. Would it be improved if every single call to printf had to prefix it with an explicit "I don't care about the return value" bit of syntax (e.g. (void)), because 99.99% of the time, you don't actually care how many bytes you printed, but printf computes and returns it anyway? Basically, you're allowed to not use the return value because there's was no need to force you to do so, and it's often not needed.
tl;dr: You can write code such that the return values are always relevant - in that case ignoring them would be a bug. However, some (particularly older) code does not work that way, there ignoring return values may be reasonable.
What is the logic as to why this okay? Was it an arbitrary design
choice from the C creators?
It is not just a choice by the C creators, many other languages also allow this - as a matter of fact, I cannot think of a language where ignoring the return value is considered an error.
The practical motivation for this is mainly that the return value of a function is often used for reporting errors, or reporting details of what the function did. Sometimes, you are not interested in these details, so you ignore them. A common example of this is the C function printf, which returns the number of characters printed. While this may sometimes be useful, it is usually not, so the return value of printf is usually ignored.
This is arguably a bad design (either in your code, or in the function that returns stuff noone wants), but it is established practice, so C (like other languages) supports this.
Or is there a practical reason for not requiring the calling function to use the return value?
No, there is no practical reason for ignoring return values - unless you do not want them.
While the above is the historical practice, many people now consider ignoring return values a problem (or a symptom of a deeper problem):
If the return value is for error reporting, ignoring it will work usually, but cause problems if there really is an error. This is now usually considered a bad idea.
Generally, if you can ignore the return value, that means the function is causing side-effects (otherwise calling it would be pointless). Many people think that it is better to have functions only do one thing - either cause a side effect (and return nothing), or return a value (and have no side effects). The latter is often called a pure function (with the additional condition of the output only depending on the input). This separation makes it easier to understand software - and if you use it, ignoring a return value is necessarily a mistake, because functions returning a result do nothing else, so if you ignore the result, calling it is pointless.
So in other words: If you follow certain conventions, there should be no situation where you want to ignore return values, in that case ignoring them is usually a mistake. Without these conventions, there may be good reasons for ignoring them, so there's no general rule.

Use of (apparently) empty C function

Can anyone comment on the point of the following function, which appears to do not very much:
// Returns stored values
int getDetails(const int param1[],
int* param2,
int* param3,
int* param4)
{
(void)param1;
(void)param2;
(void)param3;
(void)param4;
return 0;
}
The comment is actually there with the code. I'm thinking it must be some kind of odd stub but it is being called and I'm racking my brains to try to imagine what I'm missing.
My best hunch so far is that the function has been deprecated but not removed and the (void)param is to avoid compiler warnings about unused variables.
Statements like (void)param1; are typically used to suppress warnings about unused function parameters. (As an aside, in C++ you could also comment out or remove the parameter names.)
You're correct that the function does nothing. If other code doesn't create a pointer to it, you could safely remove it.
It's an empty function. Casts to void suppress warnings about unused parameters.
Such functions are often used when a function must be called unconditionally or a valid function pointer must be provided, but really the function has nothing to do.
I have a few such functions in my compiler's code generator. There are two code generators actually, one for x86 and the other for MIPS. I compile and link one or the other, never both at the same time.
The code generators are different internally but have the same external API. So, some functions specific to one CPU have some work to do while the same functions for the other have nothing to do. Logically, some of them are empty since there's nothing to do.
My guess (opinion - sorry!) that it could be a stub as you say. If you have a function that takes one or more function pointers to achieve something and it does not allow for a NULL (don't bother with this) then you have to provide something for it to call.
The casts are probably to avoid the "unused parameter" warning.
You're right, it has no point.
All it does is explicitly ignore the arguments by evaluating them and casting the result to (void), and return 0.
Is the return value being used in the context of the call? The best approach is of course to remove the call and replace it with a 0 if the return value is being used, and test the program.
Some Compilers shows error/warning when you are not using the arguments passed to it , to avoid that mention that like it in your code . If the function is not called any where or not assigned to any function pointers , you can remove it as it is not doing anything specific

What is the purpose of this return value?

I ran into some code I couldn't find an answer to on Google or SO. I am looking at a thread function which returns void* as you could expect. However, before the thread function ends it suddenly pulls this stunt,
return (void*) 0;
What is the purpose of that? I can't make any sense of it.
edit:
After understanding this is the same as NULL-- it is my thought they used this to skip including stdlib.
(void*)0 is the null pointer, a.k.a. NULL (which actually is a macro defined in several header files, e.g. stddef.h or stdio.h, that basically amounts to the same thing as (void*)0).
Update:
How to explain null pointers and their usefulness? Basically, it's a special value that says, "This pointer doesn't point anywhere," or, "This pointer is not set to a valid object reference."
Historical note: Tony Hoare, who is said to have invented null references in 1965, is known to regret that invention and thus calls it his "Billion Dollar Mistake":
Whenever you work with pointers, you must make sure to never dereference a null pointer (because it doesn't reference anything by definition). If you do it anyway, you'll either get abnormal program termination, a general protection fault, or unexpected program behaviour at the very least.
Well, I have not encountered any C++ compiler saying NULL or 0 cannot be converted to void* (or to/from int*, for example). But there might be some smart compilers or static-analysis tools that would report 0 to void-pointer conversion as a warning.
That statement is commonly found in callback implementation (like a thread-routine), which must adhere to prototype of callback being demanded (pthread_create, CreateThread etc). Therefore, when you implement that function, you must return the same type it was demanded for. For pthread_create routine, you must return a void* - and that's why return (void*)0; is there.

What is this kind of coding style in c?

(void) fputs( line, stdout );
(void) alarm( TIMEOUT );
The above appears in the function body,I've never seen such code before...
It's a form of coding to debugging tools at the expense of human beings reading your code, and it's Considered Harmful. In particular, the classic lint tool and perhaps some compilers generated warnings if you did not use the return value of a function that returned a value, and the only way to suppress this locally was to cast the result to void.
Either ignore it, or fix it (remove the useless void casts) if you have sufficient authority to do so.
The only thing unusual are the casts to void. It's a way to indicate that you're going to ignore the return value of the function, or to indicate that a function returns no value. Some compilers warn about ignored return values, so can be a way around that warning. I don't think it's very good style myself.
If you mean the (void) part, then that is explicitly discarding the result of the function call. fputs(...) returns an int. (void) fputs(...) discards the int return value without generating compiler warnings.

Function pointer cast to different signature

I use a structure of function pointers to implement an interface for different backends. The signatures are very different, but the return values are almost all void, void * or int.
struct my_interface {
void (*func_a)(int i);
void *(*func_b)(const char *bla);
...
int (*func_z)(char foo);
};
But it is not required that a backends supports functions for every interface function. So I have two possibilities, first option is to check before every call if the pointer is unequal NULL. I don't like that very much, because of the readability and because I fear the performance impacts (I haven't measured it, however). The other option is to have a dummy function, for the rare cases an interface function doesn't exist.
Therefore I'd need a dummy function for every signature, I wonder if it is possible to have only one for the different return values. And cast it to the given signature.
#include <stdio.h>
int nothing(void) {return 0;}
typedef int (*cb_t)(int);
int main(void)
{
cb_t func;
int i;
func = (cb_t) nothing;
i = func(1);
printf("%d\n", i);
return 0;
}
I tested this code with gcc and it works. But is it sane? Or can it corrupt the stack or can it cause other problems?
EDIT: Thanks to all the answers, I learned now much about calling conventions, after a bit of further reading. And have now a much better understanding of what happens under the hood.
By the C specification, casting a function pointer results in undefined behavior. In fact, for a while, GCC 4.3 prereleases would return NULL whenever you casted a function pointer, perfectly valid by the spec, but they backed out that change before release because it broke lots of programs.
Assuming GCC continues doing what it does now, it will work fine with the default x86 calling convention (and most calling conventions on most architectures), but I wouldn't depend on it. Testing the function pointer against NULL at every callsite isn't much more expensive than a function call. If you really want, you may write a macro:
#define CALL_MAYBE(func, args...) do {if (func) (func)(## args);} while (0)
Or you could have a different dummy function for every signature, but I can understand that you'd like to avoid that.
Edit
Charles Bailey called me out on this, so I went and looked up the details (instead of relying on my holey memory). The C specification says
766 A pointer to a function of one type may be converted to a pointer to a function of another type and back again;
767 the result shall compare equal to the original pointer.
768 If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.
and GCC 4.2 prereleases (this was settled way before 4.3) was following these rules: the cast of a function pointer did not result in NULL, as I wrote, but attempting to call a function through a incompatible type, i.e.
func = (cb_t)nothing;
func(1);
from your example, would result in an abort. They changed back to the 4.1 behavior (allow but warn), partly because this change broke OpenSSL, but OpenSSL has been fixed in the meantime, and this is undefined behavior which the compiler is free to change at any time.
OpenSSL was only casting functions pointers to other function types taking and returning the same number of values of the same exact sizes, and this (assuming you're not dealing with floating-point) happens to be safe across all the platforms and calling conventions I know of. However, anything else is potentially unsafe.
I suspect you will get an undefined behaviour.
You can assign (with the proper cast) a pointer to function to another pointer to function with a different signature, but when you call it weird things may happen.
Your nothing() function takes no arguments, to the compiler this may mean that he can optimize the usage of the stack as there will be no arguments there. But here you call it with an argument, that is an unexpected situation and it may crash.
I can't find the proper point in the standard but I remember it says that you can cast function pointers but when you call the resulting function you have to do with the right prototype otherwise the behaviour is undefined.
As a side note, you should not compare a function pointer with a data pointer (like NULL) as thee pointers may belong to separate address spaces. There's an appendix in the C99 standard that allows this specific case but I don't think it's widely implemented. That said, on architecture where there is only one address space casting a function pointer to a data pointer or comparing it with NULL, will usually work.
You do run the risk of causing stack corruption. Having said that, if you declare the functions with extern "C" linkage (and/or __cdecl depending on your compiler), you may be able to get away with this. It would be similar then to the way a function such as printf() can take a variable number of arguments at the caller's discretion.
Whether this works or not in your current situation may also depend on the exact compiler options you are using. If you're using MSVC, then debug vs. release compile options may make a big difference.
It should be fine. Since the caller is responsible for cleaning up the stack after a call, it shouldn't leave anything extra on the stack. The callee (nothing() in this case) is ok since it wont try to use any parameters on the stack.
EDIT: this does assume cdecl calling conventions, which is usually the default for C.
As long as you can guarantee that you're making a call using a method that has the caller balance the stack rather than the callee (__cdecl). If you don't have a calling convention specified the global convention could be set to something else. (__stdcall or __fastcall) Both of which could lead to stack corruption.
This won't work unless you use implementation-specific/platform-specific stuff to force the correct calling convention. For some calling conventions the called function is responsible for cleaning up the stack, so they must know what's been pushed on.
I'd go for the check for NULL then call - I can't imagine it would have any impact on performance.
Computers can check for NULL about as fast as anything they do.
Casting a function pointer to NULL is explicitly not supported by the C standard. You're at the mercy of the compiler writer. It works OK on a lot of compilers.
It is one of the great annoyances of C that there is no equivalent of NULL or void* for function pointers.
If you really want your code to be bulletproof, you can declare your own nulls, but you need one for each function type. For example,
void void_int_NULL(int n) { (void)n; abort(); }
and then you can test
if (my_thing->func_a != void_int_NULL) my_thing->func_a(99);
Ugly, innit?

Resources