C Constants
C - Constants and Literals
Section titled “C - Constants and Literals”In C, the term constant can refer to two related concepts:
- Literals: These are fixed values directly written in the source code, like
123,3.14,'A', or"Hello". Their type is inferred from their format. - Constant Variables: These are variables whose values cannot be modified after initialization, declared using the
constkeyword.
Literals represent values that don’t change during program execution. They can be of various basic data types.
Integer Literals
Section titled “Integer Literals”Integer literals represent whole numbers. They can be specified in different bases:
- Decimal: No prefix (e.g.,
123,-45). - Octal: Prefix
0(e.g.,077represents decimal 63). Digits 0-7 only. - Hexadecimal: Prefix
0xor0X(e.g.,0xFFrepresents decimal 255,0x1arepresents decimal 26). Digits 0-9, a-f, A-F. - Binary (C23 Standard): Prefix
0bor0B(e.g.,0b1011represents decimal 11). Note: Check compiler support for C23 features.
Integer literals can have suffixes to specify their type explicitly:
uorUforunsigned.lorLforlong.llorLLforlong long(C99 and later).
Suffixes can be combined (e.g., ul, ULL, Lu). The order doesn’t matter, and case is ignored.
Examples of integer literals:
212 // int (decimal)215u // unsigned int0xFeeL // long int (hexadecimal)076 // int (octal)456ULL // unsigned long long (C99)0b101010ul // unsigned long (binary - C23)
// Common Errors:// 078 // Illegal: 8 is not an octal digit// 0xFG // Illegal: G is not a hexadecimal digit// 32UU // Illegal: Cannot repeat the same suffix type (U)Floating-Point Literals
Section titled “Floating-Point Literals”Floating-point literals represent real numbers (numbers with a fractional part). They can be written in:
- Decimal form: Must include a decimal point, an exponent, or both (e.g.,
3.14159,123.,.456,1e-5). - Exponential form: Uses
eorEfollowed by a signed integer exponent (e.g.,314159E-5Lmeans 314159 * 10-5).
By default, floating-point literals have type double. Suffixes can specify other floating types:
forFforfloat.lorLforlong double.
Examples of floating-point literals:
3.14159 // double3.14f // float123.456L // long double1.23e10 // double (1.23 * 10^10)-5.E-2 // double (-0.05).001F // float
// Common Errors:// 510E // Illegal: incomplete exponent// 210f // Illegal: needs decimal point or exponent for float literal// .e55 // Illegal: missing integer or fraction part before exponentCharacter Constants
Section titled “Character Constants”A character constant represents a single character enclosed in single quotes (' '). Its type is int in C.
Examples: 'a', '%', '7'.
Special characters can be represented using escape sequences, which start with a backslash (\):
| Escape Sequence | Meaning |
|---|---|
\n | Newline |
\t | Horizontal tab |
\a | Alert (bell) |
\b | Backspace |
\r | Carriage return |
\f | Form feed |
\v | Vertical tab |
\\ | Backslash (\) character |
\' | Single quote (') character |
\" | Double quote (") character |
\? | Question mark (?) character (used to avoid trigraphs, now largely historical) |
\ooo | Character represented by octal value (one to three digits) |
\xhh... | Character represented by hexadecimal value (one or more digits) |
Example using escape sequences:
#include <stdio.h>
int main(void) { printf("First line.\nSecond line with\ttab.\nBell sound:\a\n"); printf("Display single quote: \' and double quote: \"\n"); printf("Character with octal 77: %c\n", '\77'); // Octal 77 is decimal 63, ASCII '?' printf("Character with hex 41: %c\n", '\x41'); // Hex 41 is decimal 65, ASCII 'A' return 0;}Output (may vary slightly based on terminal):
First line.Second line with tab.Bell sound:Display single quote: ' and double quote: "Character with octal 77: ?Character with hex 41: AString Literals
Section titled “String Literals”A string literal is a sequence of characters enclosed in double quotes (" "). It represents an array of characters automatically terminated by a null character ('\0').
Example: "Hello, world!\n". This literal creates an array containing the 14 characters plus a final '\0'.
String literals can contain escape sequences just like character constants.
Adjacent string literals are automatically concatenated by the compiler into a single string literal. This is useful for breaking long strings across multiple lines:
// These three definitions create identical strings:const char* str1 = "A long string literal.";
const char* str2 = "A long " "string literal.";
const char* str3 = "A" " long" " string" " literal.";Defining Constants
Section titled “Defining Constants”There are two primary ways to define named constants in C:
- Using the
#definepreprocessor directive. - Using the
constkeyword.
The #define Preprocessor
Section titled “The #define Preprocessor”#define creates a macro. The preprocessor replaces every occurrence of the identifier with the specified value before compilation begins.
Syntax: #define IDENTIFIER value
Example:
#include <stdio.h>
#define PI 3.14159#define GREETING "Hello"#define NEWLINE '\n'
int main(void) { double radius = 5.0; double circumference = 2 * PI * radius;
printf("%s, the circumference is: %.2f%c", GREETING, circumference, NEWLINE);
return 0;}Output:
Hello, the circumference is: 31.42Advantages: Can define constants without using memory (simple text replacement). Can define macro functions (though often better alternatives exist).
Disadvantages: No type checking by the compiler. Can lead to unexpected behavior if complex expressions are used as values (use parentheses!). Not respected by debuggers in the same way as variables.
The const Keyword
Section titled “The const Keyword”The const keyword qualifies a variable declaration, indicating that its value cannot be changed after initialization. These are often called “constant variables”.
Syntax: const type variable_name = value;
Example:
#include <stdio.h>
int main(void) { const int MAX_USERS = 100; const double GRAVITY = 9.81; const char TAB_CHAR = '\t';
printf("Max users: %d%cGravity: %.2f\n", MAX_USERS, TAB_CHAR, GRAVITY);
// MAX_USERS = 150; // Error: Cannot assign to read-only variable 'MAX_USERS'
return 0;}Output:
Max users: 100 Gravity: 9.81Advantages: Type-safe (compiler checks the type). Obeys scope rules. Can be examined by debuggers. Generally preferred over #define for defining typed constants.
Note: By convention, identifiers for #define macros are often written in all uppercase (MAX_USERS). While this convention is sometimes also used for const variables, it’s not as universal; standard variable naming conventions (e.g., camelCase or snake_case) are also common for const variables.