
228 views
Constants in C
The constants are fixed values that do not change during the execution of a program. Constants are used to represent data that remains the same throughout the program’s execution, and they are often used for defining parameters, configuration values, and mathematical constants. C supports different types of constants, including:
- Integer Constants:
- Integer constants represent whole numbers, and they can be written in decimal, octal (base 8), or hexadecimal (base 16) notation.
- Examples:
- Decimal:
42
,-123
- Octal:
075
(prefixed with0
) - Hexadecimal:
0x1A
or0X1A
(prefixed with0x
or0X
)
- Decimal:
- Floating-Point Constants:
- Floating-point constants represent real numbers with decimal points. They can have a fractional part and/or an exponent part.
- Examples:
3.14159
,-0.01
,1.0
,2.5e3
(scientific notation)
- Character Constants:
- Character constants represent individual characters and are enclosed in single quotes.
- Examples:
'A'
,'7'
,'%'
- String Constants:
- String constants represent sequences of characters enclosed in double quotes.
- Example:
"Hello, World!"
- Enumeration Constants:
- Enumeration constants are user-defined constants created using the
enum
keyword. They represent a set of named integer values. - Example:
c enum Days { MON, TUE, WED, THU, FRI, SAT, SUN };
- Symbolic Constants (Macros):
- Symbolic constants are defined using the
#define
preprocessor directive. They provide a way to create named constants in your code. - Example:
c #define PI 3.14159
- Boolean Constants:
- While C does not have dedicated boolean constants,
0
is often used to represent “false,” and non-zero values (usually1
) represent “true.”
- NULL Pointer Constant:
- The special constant
NULL
represents a null pointer and is often used for initializing pointers. - Example:
int *ptr = NULL;
Constants are used in C to make programs more readable, maintainable, and flexible. They allow you to define values once and use them throughout your code, making it easier to update and modify those values in the future.