C Constants
--
C Language TutorialC IntroductionC Environment SetupC VScodeC Program StructureC Basic SyntaxC Data TypesC VariablesC ConstantsC Storage ClassesC OperatorsC Decision MakingC LoopsC FunctionsC Scope RulesC ArraysC enum (Enumeration)C PointersC Function Pointers and Callback FunctionsC StringsC StructuresC UnionsC Bit FieldsC typedefC Input & OutputC File I/OC PreprocessorsC Header FilesC Type CastingC Error HandlingC RecursionC Variable ArgumentsC Memory ManagementC Undefined BehaviorC Command Line ArgumentsC Safe FunctionsC Sorting AlgorithmsC Project StructureC ExamplesC Classic 100 ExamplesC Quiz C Standard Library - Reference Manual<a href="#" title="C Standard Library - ">C Standard Library -
C Tutorial
C Standard Library
C Constants
Constants are fixed values that do not change during program execution. These fixed values are also called literals.
Constants can be any basic data type, such as integer constants, floating-point constants, character constants, or string literals, and also enumeration constants.
Constants are like regular variables, except that their values cannot be modified after definition.
Constants can be used directly in the code or by defining constants.
Integer Constants
Integer constants can be decimal, octal, or hexadecimal constants. The prefix specifies the base: 0x or 0X for hexadecimal, 0 for octal, and no prefix for decimal by default.
Integer constants can also have a suffix, which is a combination of U and L, where U represents an unsigned integer and L represents a long integer. The suffix can be uppercase or lowercase, and the order of U and L is arbitrary.
Here are some examples of integer constants:
212 /* Legal */215u /* Legal */0xFeeL /* Legal */078 /* Illegal: 8 is not an Octal digit */032UU /* Illegal: cannot duplicate suffix */
Here are examples of various types of integer constants:
85 /* Decimal */0213 /* Octal */0x4b /* Hexadecimal */30 /* Integer */30u /* Unsigned Integer */30l /* Long Integer */30ul /* Unsigned Long Integer */
Integer constants can have a suffix to indicate the data type, for example:
Example
int myInt =10;
long myLong =100000L;
unsigned int myUnsignedInt = 10U;
Floating-point Constants
Floating-point constants consist of an integer part, a decimal point, a fractional part, and an exponent part. You can use decimal form or exponential form to represent floating-point constants.
When using decimal form, you must include the integer part, the fractional part, or both. When using exponential form, you must include the decimal point, the exponent, or both. A signed exponent is introduced by e or E.
Here are some examples of floating-point constants:
3.14159 /* Legal */314159E-5L /* Legal */510E /* Illegal: incomplete exponent */210f /* Illegal: no decimal or exponent */.e55 /* Illegal: Missing Integer or fraction */
Floating-point constants can have a suffix to indicate the data type, for example:
Example
float myFloat =3.14f;
double myDouble =3.14159;
Character Constants
Character constants are enclosed in single quotes, for example, 'x' can be stored in a simple variable of type char.
A character constant can be an ordinary character (e.g., 'x'), an escape sequence (e.g., 't'), or a universal character (e.g., 'u02C0').
In C, there are certain characters that, when preceded by a backslash, have special meanings and are used to represent things like newline (n) or tab (t). The following table lists some such escape sequence codes:
| Escape Sequence | Meaning |
|---|---|
| character | |
| ' | ' character |
| " | " character |
| ? | ? character |
| a | Alert bell |
| b | Backspace |
| f | Form feed |
| n | Newline |
| r | Carriage return |
| t | Horizontal tab |
| v | Vertical tab |
| ooo | One to three digits octal number |
| xhh . . . | One or more digits hexadecimal number |
The following example shows some escape sequence characters:
Example
#includeint main(){printf("HellotWorldnn"); return 0; }
When the above code is compiled and executed, it produces the following result:
Hello World
The ASCII value of a character constant can be converted to an integer value through type casting.
Example
char myChar ='a';
int myAsciiValue =(int) myChar;// Convert myChar to ASCII value 97
String Constants
String literals or constants are enclosed in double quotes " ". A string contains characters similar to character constants: ordinary characters, escape sequences, and universal characters.
You can use spaces as separators to break a long string constant into multiple lines.
The following example shows some string constants. The strings displayed in these three forms are identical.
"hello, dear""hello, dear""hello, " "d" "ear"
String constants are terminated with a null character in memory. For example:
char myString[] = "Hello, world!"; //System automatically adds a null character to string constants ''
Defining Constants
In C, there are two simple ways to define constants:
- Using the #define preprocessor: #define can define a constant in the program, which is replaced by its corresponding value at compile time.
- Using the const keyword: The const keyword is used to declare a read-only variable, meaning the variable's value cannot be modified during program execution.
#define Preprocessor
The following is the form of defining constants using the #define preprocessor:
#define constant_name constant_value
The following code defines a constant named PI:
#define PI 3.14159
When using this constant in the program, the compiler will replace all PI with 3.14159.
See the specific example below:
Example
#include#define LENGTH 10#define WIDTH 5#define NEWLINE 'n'int main(){int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE); return 0; }
When the above code is compiled and executed, it produces the following result:
value of area : 50
const Keyword
You can declare a constant of a specified type using the const prefix, as shown below:
const data_type constant_name = constant_value;
The following code defines a constant named MAX_VALUE:
const int MAX_VALUE = 100;
When using this constant in the program, its value will always be 100 and cannot be modified.
Declaring constants with const must be done in a single statement:
See the specific example below:
Example
#includeint main(){const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = 'n'; int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE); return 0; }
When the above code is compiled and executed, it produces the following result:
value of area : 50
Please note that it is a good programming practice to define constants in uppercase letters.
Difference between #define and const
Both #define and const can be used to define constants, and the choice depends on specific needs and programming habits. Usually, it is recommended to use the const keyword to define constants because it offers advantages in type checking and scope, while #define only performs simple text substitution, which may lead to some unexpected issues.
The #define preprocessor directive and the const keyword have some differences when defining constants:
- Substitution mechanism:
#defineperforms simple text substitution, whileconstdeclares a typed constant. Constants defined with#defineare directly replaced by their corresponding values at compile time, while constants defined withconstare allocated memory at runtime and have type information. - Type checking:
#definedoes not perform type checking because it only does simple text substitution. Constants defined withconsthave type information, and the compiler can perform type checking on them. This helps catch some potential type errors. - Scope: Constants defined with
#definehave no scope restrictions and are valid throughout the code after definition. Constants defined withconsthave block-level scope and are only valid within the scope where they are defined. - Debugging and symbol table: Constants defined with
#definedo not have corresponding entries in the symbol table because they are just text substitutions. Constants defined withconsthave corresponding entries in the symbol table, which aids in debugging and readability.
YouTip