A constant is a value that does not change during a particular operation, while a literal is a value written directly in the source code. C provides different forms of literals for integers, floating-point values, characters, and strings.
#include <stdio.h>
int main()
{
int decimal = 100;
int octal = 0144;
int hexadecimal = 0x64;
float temperature = 25.5f;
char letter = 'A';
printf("Decimal = %d\n", decimal);
printf("Octal = %d\n", octal);
printf("Hexadecimal = %d\n", hexadecimal);
printf("Temperature = %.1f\n", temperature);
printf("Letter = %c\n", letter);
return 0;
}
Example Output #
Decimal = 100
Octal = 100
Hexadecimal = 100
Temperature = 25.5
Letter = A
Explanation #
An integer literal can be written using different number bases:
int decimal = 100;
int octal = 0144;
int hexadecimal = 0x64;
All three represent the same numeric value, 100, but use different representations.
A floating-point literal can include a suffix:
float temperature = 25.5f;
The f suffix specifies a float literal.
A character literal is enclosed in single quotes:
char letter = 'A';
A string literal is enclosed in double quotes:
"Hello"
String literals are covered in greater detail in the Strings module.
Common Literal Types #
| Literal | Example | Type |
|---|---|---|
| Integer | 100 |
Integer type |
| Unsigned integer | 100U |
Unsigned integer type |
| Long integer | 100L |
long |
| Long long integer | 100LL |
long long |
| Floating-point | 25.5 |
double |
| Float | 25.5f |
float |
| Long double | 25.5L |
long double |
| Character | 'A' |
int |
| String | "Hello" |
Array of char |
A character constant such as 'A' has type int in C, although it is commonly stored in a char object.