A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.
In addition, a required bit pattern can be specified using its octal equivalent. '\044' produces bit pattern 00100100. Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string to act as a string terminator. A character is a different type to a single character string. This is important poing to note. Defining ConstantsANSI C allows you to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed. The const keyword is to declare a constant, as shown below:
Note:
The preprocessor #define is another more flexible (see Preprocessor Chapters) method to define constants in a program.
Here TRUE, FALSE and NAME_SIZE are constant You frequently see const declaration in function parameters. This says simply that the function is not going to change the value of the parameter. The following function definition used concepts we have not met (see chapters on functions, strings, pointers, and standard libraries) but for completenes of this section it is is included here:
The enum Data typeenum is the abbreviation for ENUMERATE, and we can use this keyword to declare and initialize a sequence of integer constants. Here's an example:
I've made the constant names uppercase, but you can name them which ever way you want. Here, colors is the name given to the set of constants - the name is optional. Now, if you don't assign a value to a constant, the default value for the first one in the list - RED in our case, has the value of 0. The rest of the undefined constants have a value 1 more than the one before, so in our case, YELLOW is 1,GREEN is 2 and BLUE is 3. But you can assign values if you wanted to:
Now RED=1, YELLOW=2, GREEN=6 and BLUE=7. The main advantage of enum is that if you don't initialize your constants, each one would have a unique value. The first would be zero and the rest would then count upwards. You can name your constants in a weird order if you really wanted...
|
Using Constants
Subscribe to:
Post Comments (Atom)
C Tutorials
- C - Programming HOME
- C - Basic Introduction
- C - Program Structure
- C - Reserved Keywords
- C - Basic Datatypes
- C - Variable Types
- C - Storage Classes
- C - Using Constants
- C - Operator Types
- C - Control Statements
- C - Input and Output
- C - Pointing to Data
- C - Using Functions
- C - Play with Strings
- C - Str Datatypes
- C - Working with Files
- C - Bits Manipulation
- C - Pre-Processors
- C - Useful Concepts
0 comments:
Post a Comment