Assign values before run-time

I have two constants, but the value of the second one depends on the value of the first constant.

for example:

const int value1 = 10;
const int doubleOfValue1 = 20;

but I don't want to modify the value of the "doubleOfValue1" constant manually every time I change the "value1", I wanted to make the compiler/pre-processor to make that multiplication automatically

I could make this:

const int value1 = 10;
const int doubleOfValue1 = value1*2;

but if I understand it right, that multiplication is computed in run-time in the arduino, but i don't want the arduino to make that multiplication.

There is a way to do what i want? I know #define, but I think it doesn't help with this problem...

If it's contingent on something else then it's a variable not a constant.

The compiler evaluates all constant expressions at compile time. Only expressions with variable operands have to be evaluated at runtime.

1 Like

Luckily for you, that's an incorrect understanding. To guarantee that the multiplication can done at compile time:


constexpr int value1 = 10;
constexpr int doubleOfValue1 = value1 * 2;
1 Like

Or a function. Either way, you want computed on fetch.

Mind you, a function to do it is simple, and can even be inlined:

inline int doubleOfValue1()
{
    return value1 * 2;
}
1 Like

Hi, @arturzahn5
Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".

This will help with advice on how to present your code and problems.

Try it,
Use this code and look in the IDE monitor, set baud to 9600.

const int value1 = 10;
const int doubleOfValue1 = value1 * 2;

void setup()
{
  Serial.begin(9600);
  Serial.print("value1 = ");
  Serial.print(value1);
  Serial.print("\t doubleOfValue1 = ");
  Serial.println(doubleOfValue1);
}

void loop()
{
  // put your main code here, to run repeatedly:
}

Tom... :grinning: :+1: :coffee: :australia:

1 Like

Of course for simple arithmetic, there’s always the venerable pre-processor directives…

In this case simple #define sentences would handle these with zero runtime overhead.

Could you provide an example where a pre-processor directive would cause less runtime overhead than the constant expressions?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.