I am teaching myself C by going over my C++ book and recoding the problems in C. I wanted to know the correct industry standard way of declaring variables constant in C. Do you still use the #define directive outside of main, or can you use the C++ style const int inside of main?
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
As the name suggests the name constants are given to such variables or values in C/C++ programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants, etc.
Constants are basically variables whose value can't change. In C/C++, the keyword const is used to declare these constant variables. In Java, you use the keyword final .
The const keyword is used to define constant in C programming. Now, the value of PI variable can't be changed.
const
in C is very different to const
in C++.
In C it means that the object won't be modified through that identifier:
int a = 42;
const int *b = &a;
*b = 12; /* invalid, the contents of `b` are const */
a = 12; /* ok, even though *b changed */
Also, unlike C++, const objects cannot be used, for instance, in switch labels:
const int k = 0;
switch (x) {
case k: break; /* invalid use of const object */
}
So ... it really depends on what you need.
Your options are
#define
: really const but uses the preprocessorconst
: not really constenum
: limited to int
larger example
#define CONST 42
const int konst = 42;
enum /*unnamed*/ { fixed = 42 };
printf("%d %d %d\n", CONST, konst, fixed);
/* &CONST makes no sense */
&konst; /* can be used */
/* &fixed makes no sense */
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