Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>No, in general you should not use const-qualified objects in C to create names constants. In order to create a <em>named constant</em> in C you should use either macros (<code>#define</code>) or enums. In fact, C language has no constants, in the sense that you seem to imply. (C is significantly different from C++ in this regard)</p> <p>In C language the notions of <em>constant</em> and <em>constant expression</em> are defined very differently from C++. In C <em>constant</em> means a <em>literal value</em>, like <code>123</code>. Here are some examples of <em>constants</em> in C</p> <pre><code>123 34.58 'x' </code></pre> <p>Constants in C can be used to build <em>constant expressions</em>. However, since const-qualified objects of any type are not a <em>constants</em> in C, they cannot be used in constant expressions, and, consequently, you cannot use const-qualified objects where constant expressions are required. </p> <p>For example, the following is not a constant</p> <pre><code>const int C = 123; /* C is not a constant!!! */ </code></pre> <p>and since the above <code>C</code> is not a constant, it cannot be used to declare an array type in file scope</p> <pre><code>typedef int TArray[C]; /* ERROR: constant expression required */ </code></pre> <p>It cannot be used as a case label</p> <pre><code>switch (i) { case C: ; /* ERROR: constant expression required */ } </code></pre> <p>It cannot be used as bit-field width</p> <pre><code>struct S { int f : C; /* ERROR: constant expression required */ }; </code></pre> <p>It cannot be used as an initializer for an object with static storage duration</p> <pre><code>static int i = C; /* ERROR: constant expression required */ </code></pre> <p>It cannot be used as a enum initializer</p> <pre><code>enum { E = C /* ERROR: constant expression required */ }; </code></pre> <p>i.e it cannot be used anywhere where a <em>constant</em> is required.</p> <p>This might seem counter-intuitive, but this is how C the language is defined. </p> <p>This is why you see these numerous <code>#define</code>-s in the code you are working with. Again, in C language const-qualified object have very limited use. They are basically completely useless as "constants", which is why in C language you are basically forced to use <code>#define</code> or enums to declare true constants.</p> <p>Of course, in situations when a const-qualified object works for you, i.e. it does what you want it to do, it is indeed superior to macros in many ways, since it is scoped and typed. You should probably prefer such objects where applicable, however in general case you'll have to take into account the above limitations.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload