Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the standard to declare constant variables in ANSI C?

Tags:

c

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?

like image 241
J-e-L-L-o Avatar asked Jun 30 '11 23:06

J-e-L-L-o


People also ask

How do you declare a constant variable in C?

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.

What is declared constant in C programming?

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.

What is used to declare constant variable?

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 .

Which keyword is used to declare a constant variable in C language?

The const keyword is used to define constant in C programming. Now, the value of PI variable can't be changed.


1 Answers

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 preprocessor
  • const: not really const
  • enum: 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 */
like image 88
pmg Avatar answered Oct 27 '22 20:10

pmg