cfunctioncastingvoid

Casting function result into a void speed comparison


I wonder how casting function into a void will affect speed. By that i mean :

int a,b;

int main (){
  (void)my_func();
}

int my_func(){
  return a+b;
}

What would compiler do with this.

int a,b;

int main (){
  my_func();
}

int my_func(){
  return a+b;
}

Which of this blocks of code would be faster. If noone of them, then what is the purpose of writing (void) before function call


Solution

  • In C language, programmer should not care too much for low level optimizations(*). The mantra says the compiler is smarter than you. That means that such low level details are normally handled by the optimizing compilers.

    What should matter are:

    Here the (void) cast mainly says that the programmer willingly discarded the return value and that they did not forget it by mistake.


    (*) As for any rule, there are of course exceptions. When you are writing code where execution time is critical, you should carefully profile it and care for low-level optimizations in the portions where most time is spent. But you must be aware that those optimizations only make sense on a specific architecture and a specific compiler. It was even common to use assembly language in this use case.