Cjdcoy
Cjdcoy

Reputation: 387

c - Are defined values slower than hard-coded numbers

this question might appear dumb to you but I couldn't find an answer to it and I want to be sure that it works as I think.

Recently I came across this code:

void RDP_G_SETBLENDCOLOR(void)
{
    Gfx.BlendColor.R = _SHIFTR(w1, 24, 8) * 0.0039215689f;
    Gfx.BlendColor.G = _SHIFTR(w1, 16, 8) * 0.0039215689f;
    Gfx.BlendColor.B = _SHIFTR(w1, 8, 8) * 0.0039215689f;
    Gfx.BlendColor.A = _SHIFTR(w1, 0, 8) * 0.0039215689f;

    if(OpenGL.Ext_FragmentProgram && (System.Options & BRDP_COMBINER)) {
        glProgramEnvParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 2, Gfx.BlendColor.R, Gfx.BlendColor.G, Gfx.BlendColor.B, Gfx.BlendColor.A);
    }
}

I understand that the 0.0039215689f (which refers to 1/255) is hard-coded for optimization reasons. Now imagine that I want to define it for readability reasons (even if the name chosen here is not better, it's just for the example).

#define PIXEL_VALUE 0.0039215689f

void RDP_G_SETBLENDCOLOR(void)
{
    Gfx.BlendColor.R = _SHIFTR(w1, 24, 8) * PIXEL_VALUE;
    Gfx.BlendColor.G = _SHIFTR(w1, 16, 8) * PIXEL_VALUE;
    Gfx.BlendColor.B = _SHIFTR(w1, 8, 8) * PIXEL_VALUE;
    Gfx.BlendColor.A = _SHIFTR(w1, 0, 8) * PIXEL_VALUE;

    if(OpenGL.Ext_FragmentProgram && (System.Options & BRDP_COMBINER)) {
        glProgramEnvParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 2, Gfx.BlendColor.R, Gfx.BlendColor.G, Gfx.BlendColor.B, Gfx.BlendColor.A);
    }
}

Would this define make the code execution slower?

Upvotes: 2

Views: 114

Answers (3)

iBug
iBug

Reputation: 37227

I believe they make no difference at all.

A macro is a pattern of text replacement. So it gets replaced before your code is compiled.

You can try preprocessing both files and see the difference in a terminal:

gcc -E 1.c -o 1.i
gcc -E 2.c -o 2.i
diff -u 1.i 2.i

Upvotes: 1

gnasher729
gnasher729

Reputation: 52538

Macros do text replacement. The code that gets compiled is exactly the same as if you copied and pasted the replacement text of the macro in your code.

Upvotes: 2

gsamaras
gsamaras

Reputation: 73366

Would this define make the code execution slower?

No, since these two code snippets are identical, because MACROS are expanded before a translation unit is compiled.

Upvotes: 6

Related Questions