开发者

What is the standard to declare constant variables in ANSI 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 开发者_StackOverflow#define directive outside of main, or can you use the C++ style const int inside of main?


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 */


Modern C supports both #defines and const globals. However, #defines are usually preferred for true constants; this is because #defines can be inlined into the place where they are used, while const globals generally require a memory read, particularly if they're defined in a different translation unit.

That said, complex constant structures are a good use for const globals - strings, structs, arrays, etc.


In most modern implementations the compiler is trying to do more just to bare the access via the symbol by placing the global const variables in the read only sections. It actually protects them on many systems against change. Some examples : segfault on Linux systems and errors on Windows or placing the code in the FLASH when using the micro controllers.

It is of course 100% implementation, but it is good to know that modern machines with memory protection hardware and modern compilers do more than only follow the standard


Variables qualified by const are not considered compile-time constant, they have one significant limitation: const int cannot be used to define the size of an array.(historical reasons but not a limitation of the compiler, C++ corrects this oversight though)

You can choose:

#define SIZE 5   /* preprocessor */
enum { SIZE=5 }; /* compiler */


The standard that is followed in most C programs is to have all constants as macros (#define) in a separate header file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜