Home > Software design >  C function that only returns input parameter
C function that only returns input parameter

Time:07-30

For reasons out of my control, I have to implement this function in my C code:

double simple_round(double u)
{
    return u;
}

When this function is called, is it ignored by the compiler, or does the call take place anyway? For instance:

int y;
double u = 3.3;

y = (int)simple_round(u*5.5); //line1
y = (int)u*5.5;               //line2

Will both lines of code take the same time to be executed, or will the first one take longer?

CodePudding user response:

Because the function is defined in a different C file from where it's used, if you don't use link-time optimization, when the compiler calls the function call it won't know what the function does, so it will have to actually compile the function call. The function will probably just have two instructions: copy the argument to the return value, then return.

The extra function call may or may not slow down the program, depending on the type of CPU and what else the CPU is doing (the other instructions nearby)

It will also force the compiler to consider that it might be calling a very complicated function that overwrites lots of registers (whichever ones are allowed to be overwritten by a function call); this will make the register allocation worse in the function that calls it, perhaps making that function longer and making it need to do more memory accesses.

CodePudding user response:

If the 'generated' code has to be compiled anyway, perhaps you can 'kludge' a macro, Macro, that redefines the call to the 'inefficient' rounding function made by that code.

Here's a notion (all in one file). Perhaps the #define can be 'shimmed in' (and documented!) into the makefile entry for that single source file.

int fnc1( int x ) { return 5 * x; }

void main( void ) {
    printf( "%d\n", fnc1( 5 ) );

#define fnc1(x) (x)

    printf( "%d\n", fnc1( 7 ) );
}

Output:

25
7
  • Related