Types of Constants in C
In C programming, constants are fixed values that do not change during program execution. They are used to represent unchanging data, such as numerical values, characters, or special symbols. There are two main types of constants in C: literal constants and symbolic constants.
Literal constants are explicit values used directly in the code.
They can be of several types:
These represent whole numbers and can be written in decimal (base 10), octal (base 8, preceded by '0'), or hexadecimal (base 16, preceded by '0x') format.Example: 42, 077, 0x1A
These represent real numbers and include a decimal point or an exponent (e.g., e or E).Example: 3.14, 2.0e3, 0.1E-5
These represent individual characters and are enclosed in single quotes.
These represent sequences of characters and are enclosed in double quotes.Example: "Hello, World!", "C programming"
Symbolic Constants (Using const and #define)
Symbolic constants are named values that make the code more readable and maintainable. They are defined at the beginning of a program and used throughout.
There are two common ways to define symbolic constants:
Using const Keyword
Symbolic constants can be defined using the const keyword, which specifies that a variable's value should not change after initialization.
Using #define Preprocessor Directive
The #define preprocessor directive creates symbolic constants using a macro. They are replaced with their values during preprocessing.
Symbolic constants are preferred when you want to give meaningful names to values, making the code more self-explanatory and easier to maintain. Literal constants, on the other hand, are used when specific values are needed directly in the code.
Enumerated constants are constants that are defined by the programmer. Enumerated constants are declared using the enum keyword.
This enum defines seven constants, each representing a day of the week.
Constants in C programming are fixed values that remain unchanged during program execution. They are used to represent unvarying data, such as numerical values, characters, or strings. Constants can be either literal, defined directly in the code, or symbolic, given meaningful names for improved readability and maintainability.