Home > front end >  (void) vs void as the return type of a function in C
(void) vs void as the return type of a function in C

Time:09-22

I'm maintaining an application that incorporates C , C and a few python files; and all executables are build using CMake.

I noticed a few functions that are using the (void) cast.

Example:

main.c:

   typedef void CxType;

   int foo(CxType *, const char *, const char *, int , int *);

// c is a template 
// QString &s;
// QMapData::Node *e;
// QScopedPointer<QDataStreamPrivate> d;
// v is another template

   #define foo2(c,s,e,d,v) foo(c,s,e,d,v)
 
   static void some_function( void )
   {

     (void) foo(param1,param2,...);

   }

According to the O'Reilly "C Pocket reference"; (void) can be used to explicitly discard the value of an expression in C; For example: (void)printf("An example.")

Why use (void) foo(param1,param2,...); instead of simply foo(param1,param2,...);?

CodePudding user response:

The cast to void is there to suppress a compiler warning about unused return value.

// at least that was most probably the intention of the genius that came up with the cast.

CodePudding user response:

Typically you would only cast an expression to void in one of two cases.

First, if a function takes a parameter that you know isn't being used but the parameter can't be removed because the function in question is being used as a callback.

Second, if you're calling a function that has an compiler-specific attribute that causes it to warn if the function's return value isn't used, but you know you don't need to read it.

Neither of these cases apply to the above code, so the cast isn't needed.

CodePudding user response:

I admit to using the (void) foo() cast style myself; the rationale is to indicate that I know the function returns a value, which I'm deliberately ignoring. That is, it is for the reader (e.g., my future self) rather than to suppress compiler warnings, since popular C compilers do not warn about this (except perhaps with non-standard annotations on specific functions).

  •  Tags:  
  • c
  • Related