...
Wiki Markup |
---|
When used in program logic, literals can reduce the readability of source code. As a result, literals in general, and integer constants in particular, are frequently referredcalled to as _magic numbers_ because their purpose is often obscured. Magic numbers may be constant values that represent either an arbitrary value (such as a determined appropriate buffer size) or a malleable concept (such as the age a person is considered an adult, which can change between geopolitical boundaries). Rather than embed literals in program logic, use appropriately named symbolic constants to clarify the intent of the code. In addition, if a specific value needs to be changed, reassigning a symbolic constant once is more efficient and less error prone than replacing every instance of the value \[[Saks 02|AA. C References#Saks 02]\]. |
...
const
-qualified Objects
Objects that are const
-\qualified have scope and can be type-checked by the compiler. Because these are named objects (unlike macro definitions), some debugging tools can show the name of the object. The object also consumes memory.
A const
-qualified object allows you to specify the exact type of the constant. For example,
Code Block |
---|
const unsigned const int buffer_size = 256; |
defines buffer_size
as a constant whose type is unsigned int
.
...
Wiki Markup |
---|
{{const}}\-qualified objects are likely to incur some runtime overhead \[[Saks 01b|AA. C References#Saks 02]\]. Most C compilers, for example, allocate memory for {{const}}\-qualified objects. {{const}}\-qualified objects declared inside a function body may have automatic storage duration. If so, the compiler will allocate storage for the object, and it will be on the stack. As a result, this storage will need to be allocated and initialized each time the containing function is invoked. |
...
Enumeration constants can be used to represent an integer constant expression that has a value representable as an int
. Unlike const
-qualified objects, enumeration constants do not consume memory. No storage is allocated for the value, so it is not possible to take the address of an enumeration constant.
...
Replacing numeric constants with symbolic constants in this example does nothing to improve the readability of the code , and may actually make the code more difficult to read.
...
Note that this example does not check for invalid operations (taking the sqrt()
of a negative number). See FLP32-C. Prevent or detect domain and range errors in math functions, for more information on detecting domain and range errors in math functions.
...