Const VS Defines
-
1. Your solution, while removing the problems with #define, still has the problem of tight coupling of the caller's code with the library. 2. In C99 or later, variable-length arrays are perfectly legal, but IIRC - not as static variables.
If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill
1. you are free to move the initialization of the struct elsewhere within your library code. I just did it like this to have a compact example. (and I didn't want to bother finding out how and where to place qualifiers) 2. True, but that didn't help in the example code I gave. The compiler still issued an error (VS 2010, compiled "as C"). The reason I pointed out the alternative (defining an enum) is that sometimes you do want a symbol to be recognized and treated as constant (e. g. to prevent typos such as
if (MAX_SIZE=10)
), but at the same time you want to use these same constants in situations that specifically require constants, such as in array definitions. C unfortunately doesn't allow you to use aconst int
as array bounds, in spite of VLAs! But it does let you use enum values.GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)