C
C#16mo ago
Athrqk

✅ Does arithmetic in a `const float` gets recomputed each time you access it?

I know this is a bit dummy question but just want to confirm whether it would be automatically handled by the compiler.
5 Replies
phaseshift
phaseshift16mo ago
no (it does not get computed each time)
Athrqk
Athrqk16mo ago
Alright thank you
Kippachu
Kippachu16mo ago
When you declare a const float and initialize it with a value or an arithmetic expression, the value is computed at compile-time, and it remains constant throughout the program. The compiler treats constant expressions as fixed values, and it may optimize the code further by replacing the constant variable with its value directly in the compiled code. Here's an example:
const float pi = 3.14159;
const float doublePi = pi * 2;
const float pi = 3.14159;
const float doublePi = pi * 2;
In this example, doublePi will be calculated at compile-time, and its value will be stored as a constant. Each time you access doublePi, the value will not be recomputed – it will simply return the precomputed constant value.
Athrqk
Athrqk16mo ago
I see, thanks for clarifying this for me 👍
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.