Home > Blockchain >  Change alpha component in a function returning a float *color
Change alpha component in a function returning a float *color

Time:02-20

I've got a function returning a (float *) color. It works, until I tried to change the alpha component of one color, and now almost all colors have alpha issue, even if the color don't pass the test "if (alpha)".

eg:
float * colorTest = getColor(0); // don't give me the good result anymore, once any getColor(1) is called before.

float * getColor(float alpha) {
    float * col;

    if (val == 1)
        col = colorWhite; // colorWhite is a float *
    else if (val == 2)
        col = colorRed;
    else if (etc..)
        col = colEtc;

    if (alpha) {
        col[3] = alpha; // this doesn't works
    }

    return col;
}

I also have tried to change the alpha value through the col pointer, with same result:

if (alpha) {
    float *a;
    a = (float *)(&col   3);
    *a = alpha;
}

Any advice?

Edit

Got it to works, thx to hyde who told me that I was changing my global colors. (I was used to falsely considered float * as array) So, I just copy the result in a second variable and then modify this new color.

float * getColor(float alpha) {
    float * col;
    float * tmp;

    if (val == 1)
        tmp = colorWhite; // colorWhite is a float *
    else if (val == 2)
        tmp = colorRed;
    else if (etc..)
        tmp = colEtc;

    memcpy(col, tmp, sizeof(float)*4);

    if (alpha) {
        col[3] = alpha; // this now works without issue
    }

    return col;
}

CodePudding user response:

if (alpha) {
    col[3] = alpha; // this doesn't works
}

Here col points to one of your global colors. And then you change it.

Since color is small (4 floats, I assume), just pass values and forget pointers. Do this by defining struct

struct color {
    float component[4];
    // Or if you prefer: float r, g, b, a;
};

Especially on a 64 bit system, pointer is probably half the size of this struct, and has pointer dereference overhead, so performance-wise it's the basically the same. And pointers are always messier than values.

Once you have working code with struct values, then you can consider using pointers to optimize, eg. const struct color *param as function argument. But, this really is very small optimization with 4 floats. If the struct is passed in 2 registers, then forcing it to be in memory so you can pass a pointer in 1 register may even be a pessimization.


Additionally, you usually don't want to accidentally change the global data like these global colors, so make them const.

  • Related