What is the standard for declaring constant variables in ANSI C?

I teach myself C by switching my book to C ++ and rewriting problems in C. I wanted to know the right standard standard way to declare variable constants in C. Are you still using the #define directive outside the main one or can you use the const int style inside the main ?

+4
source share
3 answers

const in C is very different from const in C ++.

In C, this means that the object will not be modified through this identifier:

 int a = 42; const int *b = &a; *b = 12; /* invalid, the contents of `b` are const */ a = 12; /* ok, even though *b changed */ 

In addition, unlike C ++, const objects cannot be used, for example, 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

  • #define : really const, but uses a 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 */ 
+3
source

Modern C supports both #define and const global. However, #define usually preferred for true constants; this is because #define can be embedded in the place where they are used, and global const values ​​usually require a memory read, especially if they are defined in a different translation unit.

However, complex constant structures are useful for const globals - strings, struct s, arrays, etc.

+2
source

The standard that is followed by most C programs is that all constants be like macros (#define) in a separate header file.

0
source

All Articles