Search code examples
cperformancevariablestemporary

C: Performant temporary variables to avoid frequent typecasting


((My_LengthilyNamedClass *)this)->someMember

...I am getting tired of these appearing all over my codebase, many times even within the same function.

What is the appropriate way to handle such things in C? I'm aware that copying this to a correctly-typed stack/automatic variable with a shorter name is one approach to avoid the casts, but I suppose this would cause additional, potentially unnecessary stack allocations.

Can one use a define inside of individual functions, to make this easier? Are defines the way to go? As this is code for a real-time processing framework, and these things appear everywhere, I'd ideally like to stick to whatever's most performant.


Solution

  • Compilers are pretty good at optimizing. I think you would have no problems with:

    My_LengthilyNamedClass *const ptr = this;
    

    If you are really paranoid you could use a macro:

    #define THIS ((My_LengthilyNamedClass *)this)
    
    THIS->someMember = 5;
    
    #undef THIS