I know that I can declare a named compile-time constant in C for integers by using enums, but is there a way to declare named compile-time constants in C for floats as well, without using macros (I know that C++ has constexpr, but I am strictly using C right now)? Answers containing compiler-specific C-language extensions are also greatly appreciated.
Asked
Active
Viewed 358 times
1
-
2What is the context that requires you to have a compile time constant float? – eerorika Nov 06 '17 at 01:03
-
@user2079303 I like making sure that my constant variables are being compiled to immediates. – Cpp plus 1 Nov 06 '17 at 01:05
-
1Don't you think your compiler will know how to do the right thing? Any examples of where it breaks badly? – Bo Persson Nov 06 '17 at 01:17
-
2There's no floating point equivalent of `enum` – M.M Nov 06 '17 at 01:22
-
2You’ll need to use a macro in C. – Jonathan Leffler Nov 06 '17 at 01:25
-
@Cppplus1 "making sure that my constant variables are being compiled to immediates." is interesting. Why is this important for your code? – chux - Reinstate Monica Nov 06 '17 at 02:14
-
@chux Performance, since if declaring a floating-point compile time constant is possible, why not just ensure that the floating-point numbers are compiled to the fastest instruction mode? – Cpp plus 1 Nov 06 '17 at 02:22
-
@Cppplus1 "why not just ensure that they are constants and compiled to immediates?" --> because that might not be the fastest. IAC, `123.456`, `1e10`, `0x1.2Ap21` are 3 examples of _floating-constants_. How are those _floating-constants_ of that form not sufficient for your C code? – chux - Reinstate Monica Nov 06 '17 at 04:24
-
1@chux OP is asking for named constants... – Antti Haapala -- Слава Україні Nov 06 '17 at 04:34
-
@AnttiHaapala Fair enough. Perhaps a better question would be what is insufficient about using `#define` like `#define MY_PI 3.14` `#define MY_C ((double){ 299792458.0 })`? – chux - Reinstate Monica Nov 06 '17 at 04:39
-
2(a) What you are asking for—declaring constants—is not want you want—fast code or small code. The compiler makes its own decisions about whether to use immediates, to load constants from a read-only data page, to calculate constants on the fly, to fold constants into larger expressions, or other options. (b) You can declare constants with `static const float foo = value;`. (c) What you want is likely not helpful; the time it takes to load constants is almost certainly not what is slowing your code significantly. – Eric Postpischil Nov 06 '17 at 05:58
-
Since you mentioned Compiler Specific also OK. This kinda makes it that OK too, check something called Type Punning, I think this is what you are looking for. – the kamilz Nov 07 '17 at 06:37
1 Answers
-1
Use array of const float.
Which will produce constant data of type float.
const float *arr[3] = {11.21,21.31,31.23}

Prince
- 21
- 2