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
gfvalvo
December 28, 2021, 2:57am
4
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".
See also FAQ - Arduino Forum for general rules on forum behaviour and etiquette.
Hello,
Welcome to the Arduino Forum.
This guide explains how to get the best out of this forum. Please read and follow the instructions below.
Being new here you might think this is having rules for the sake of rules, but that is not the case. If you don’t follow the guidelines all that happens is there is a long exchange of posts while we try to get you to tell us what we need in order to help you, which is fru…
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...
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?
system
Closed
June 26, 2022, 2:45pm
9
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.