I've having trouble understanding what is the point of Symbolic Constants in C, I am sure there is a reason for them but I can't seem to see why you wouldn't just use a variable.
#include <stdio.h>
main()
{
float fahr, celsius;
float lower, upper, step;
lower = 0;
upper = 300;
step = 20;
printf("%s\t %s\n", "Fahrenheit", "Celsius");
fahr = lower;
while (fahr <= upper) {
celsius = (5.0 / 9.0) * (fahr - 32.0);
printf("%3.0f\t\t %3.2f\n", fahr, celsius);
fahr = fahr + step;
}
}
Vs.
#include <stdio.h>
#define LOWER 0
#define UPPER 300
#define STEP 20
main()
{
float fahr, celsius;
printf("%s\t %s\n", "Fahrenheit", "Celsius");
fahr = LOWER;
while (fahr <= UPPER) {
celsius = (5.0 / 9.0) * (fahr - 32.0);
printf("%3.0f\t\t %3.2f\n", fahr, celsius);
fahr = fahr + STEP;
}
}
The (pre)compiler knows that symbolic constants won't change. It substitutes the value for the constant at compile time. If the "constant" is in a variable, it usually can't figure out that the variable will never change value. In consequence, the compiled code has to read the value from the memory allocated to the variable, which can make the program slightly slower and larger.
In C++, you can declare a variable to be const
, which tells the compiler pretty much the same thing. This is why symbolic constants are frowned upon in C++.
Note, however, that in C (as opposed to C++) a const int
variable is not a constant expression. Therefore, trying to do something like this:
const int a = 5;
int b[a] = {1, 2, 3, 4, 5};
will work in C++ but will get you a compilation error in C (assuming b
was supposed to be a statically bound array).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With