Constants play a crucial role in C programming, providing fixed values that do not change during program execution. Here are some important points to remember when dealing with constants in C:
Integer Constants
- Long Constants: A long integer constant is written with an ‘L’ or ‘l’ suffix. For example:
long num1 = 1234567697L; long num2 = 567874338l; // Avoid using 'l' (lowercase) as it can be confused with '1' - Unsigned Constants: An unsigned integer constant is written with a ‘U’ or ‘u’ suffix:
unsigned int positiveNum = 40000U; - Unsigned Long Constants: These constants have both ‘U’ and ‘L’ suffixes:
unsigned long bigPositiveNum = 123456789UL;
Floating-Point Constants
Floating-point constants must contain a decimal point, an exponent (e.g., 1e-1), or both. They are automatically treated as double unless explicitly declared otherwise:
double pi = 3.14159;
float gravity = 9.8F;
double smallValue = 1.23e-4; // 1.23 × 10⁻⁴
Octal and Hexadecimal Representation
Integer values can be specified in decimal, octal, or hexadecimal notation:
int decimalNum = 31; // Decimal
int octalNum = 031; // Octal (leading 0 means octal, equivalent to 25 in decimal)
int hexNum = 0x1F; // Hexadecimal (leading 0x means hex, equivalent to 31 in decimal)
Character and String Constants
- Character Constants: A character constant is essentially an integer representing the corresponding ASCII value.
char ch = 'A'; // ASCII value is 65 - String Constants (String Literals): A string constant is a sequence of characters enclosed in double quotes.
char greeting[] = "Hello, C!";
Constant Expressions
A constant expression is an expression that consists only of constants. Such expressions are evaluated at compile time.
#define PI 3.14159
const int maxValue = 100;
int area = 5 * 10; // Constant expression evaluated at compile-time
Constants in Control Flow Statements
- Switch Statements: Each
caselabel must be associated with an integer constant or a constant expression.switch (choice) { case 1: printf("Option 1 selected\n"); break; case 2 + 1: // Constant expression printf("Option 3 selected\n"); break; default: printf("Invalid option\n"); } - Continue Statement:
- In
whileanddo-whileloops,continueimmediately jumps to the condition check. - In
forloops, it moves to the increment step. - It does not apply to
switchstatements.
for (int i = 0; i < 5; i++) { if (i == 2) continue; // Skips printing '2' printf("%d ", i); }Output:0 1 3 4 - In
By keeping these fundamental points in mind, you can write cleaner and more efficient C programs.