I’m very new to C and I’m writing a Ruby C Extension. One of the functions should compute a bland between two colours. The Color struct uses char to store the RGB values. The blending ratio is a double between 0.0 and 1.0.
Is it bad practice to mix char and double in an operation I have done here? Could there be potential problems?
I’m guessing that if weight is not between 0.0 and 1.0 the could be problems as it might result in a value smaller than 0 or larger than 255.
Should I be explicitly casting types?
typedef struct Color Color;
static struct Color {
unsigned char red, green, blue, alpha;
};
static Color
color_blend( Color color1, Color color2, double weight )
{
Color color3 = { 0, 0, 0, 0 };
color3.red = ( 1 - weight ) * color1.red + ( weight * color2.red );
color3.green = ( 1 - weight ) * color1.green + ( weight * color2.green );
color3.blue = ( 1 - weight ) * color1.blue + ( weight * color2.blue );
color3.alpha = ( 1 - weight ) * color1.alpha + ( weight * color2.alpha );
return color3;
}
You don’t need to perform explicit casting; the compiler’s implicit casting should do the same thing. However, there are two good reasons to consider explicit casts:
I don’t think there will be any range issues with your code. However, you might consider adding round-to-nearest behaviour, as currently a computed value of e.g. 99.999 will truncate to 99.