'Can I make a calculation with a value outside of the range of my variable?
I'm coding in C and I know the values that can be stored in a uint8_t range from 0 to 255. I want to store a value that is the percentage of MAX_INTENSITY, declared as:
#define MAX_INTENSITY 200
Can I do the following:
uint8_t my_intensity = (MAX_INTENSITY * percentage) / 100; ?
The result will be 200 or less, but during the calculation, the intermediate result can be superior to 255, e.g. with percentage = 50, MAX_INTENSITY * percentage = 10'000. Can this cause a problem, even if the final result will be 100, o in the range of a uint8_t?
Solution 1:[1]
In C, the rules to determine the type used for each intermediary computation are somewhat intricate, but for your particular case quite easy:
The multiplication MAX_INTENSITY * percentage involves an integer constant 200 of type int and a variable percentage. If the type of percentage is int or a smaller type such as uint8_t, this operand will undergo an integer promotion to type int and the result will have type int, then used as an operand for the division by 100, another integer constant with type int, hence a computation with type int and a result of the same type. The result will be converted to the type of the destination, uint8_t, which is performed by take the positive modulo 256, a fully defined operation, especially if percentage is known to be in range 0 to 200.
Therefore, your definition is correct:
uint8_t my_intensity = (MAX_INTENSITY * percentage) / 100;
You might nevertheless consider using type int for this local variable, as there is no benefit in typing it with a smaller type in this context.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chqrlie |
