# Functions Question

• 01-09-2009
audinue
Functions Question
Code:

```/**  * RANDOM(high)  * Create random number between 0 and {high}  *  * @param high any number >= 0  */```
Code:

```/**  * RANDOM_RANGE(low, high)  * Create random number between {low} and {high}  *  * @param low  any number  * @param high any number >= {low}  */```
.
.
Which is better and why?

Code:

```#define RANDOM_RANGE(low, high) (rand() % (high - low + 1) + low) #define RANDOM(high)            (rand() % (high + 1))```
Or

Code:

```#define RANDOM_RANGE(low, high) (rand() % (high - low + 1) + low) #define RANDOM(high)            RANDOM_RANGE(0, high)```
How about if this kind of coding applied to functions?
Does it affect performance/code size?

• 01-09-2009
Elysia
RANDOM just produces a number between 0 and High.
RANDOM_RANGE produces a number in the range low to high.
Whichever you need.
Although, in unoptimized form, RANDOM is faster (less operations).
In optimized code, I do not know if it matters.
Still, performance is negligible.
• 01-09-2009
matsp
Constant folding is one of the first things that an optimizing compiler does - constant folding is where it "computes the result of multiple constants".

Code:

```#define RANDOM_RANGE(low, high) (rand() % (high - low + 1) + low) #define RANDOM(high)            (rand() % (high + 1))```
Code:

`#define RANDOM(high)            RANDOM_RANGE(0, high)`
So the compiled code will be identical, since low = 0 means that all that remains of the calculation is the same as your other macro (assuming optimization is enabled - discussing the optimization, code efficiency/size or other such without optimization is meaningless).

--
Mats