Literals are fixed values directly used in the code that represent data. They are constant values that are assigned to variables and cannot be modified. Unlike variables, literals do not occupy memory for storage in the same way because they are simply values used directly in the code. Here’s an overview of the different types of literals in C:
Description: Represent whole numbers without any fractional or exponential parts.
• Decimal (base 10): Numbers from 0 to 9, e.g., 45, 67.
• Octal (base 8): Numbers prefixed with 0, using digits 0 through 7, e.g., 012, 034.
• Hexadecimal (base 16): Numbers prefixed with 0x or 0X, using digits 0 through 9 and letters a through f, e.g., 0x2a, 0x7b.
<#include <stdio.h>>
int main() {
const int decimal = 45;
const int octal = 052; // Octal for decimal 42
const int hex = 0x2F; // Hexadecimal for decimal
47
printf("Decimal literal: %d\\n", decimal);
printf("Octal literal: %d\\n", octal);
printf("Hexadecimal literal: %d\\n", hex);
return 0;
}
Decimal literal: 45
Octal literal: 42
Hexadecimal literal: 47
Description: Represent numbers with fractional parts and/or in exponential form.
• Decimal: Numbers with a decimal point, e.g., 1.2, -4.5.
• Exponential: Represent large or small numbers using an exponent, e.g., 2.34e12, -5.6e-3.
<#include <stdio.h>>
int main() {
const float decimal = 4.5;
const float exponential = 1.23e4; // 12300.0
printf("Decimal float literal: %f\\n", decimal);
printf("Exponential float literal: %e\\n", exponential);
return 0;
}
Decimal float literal: 4.500000
Exponential float literal: 1.230000e+04
Description: Represent a single character enclosed in single quotes.
• Simple Character: Single characters like 'a', 'b'.
• Escape Sequences: Special characters like '\n' (newline), '\t' (tab).
• ASCII Values: Represented by their integer value, e.g., 65 corresponds to 'A'.
<#include <stdio.h>>
int main() {
const char letter = 'A';
const char newline = '\\n';
const char asciiChar = 65; // 'A'
printf("Character literal: %c\\n", letter);
printf("%c", newline);
printf("Character literal from ASCII: %c\\n", asciiChar);
return 0;
}
Character literal: A
Character literal from ASCII: A
Description: Represent a sequence of characters enclosed in double quotes. They are automatically terminated by a null character ('\0').
• Basic String: "Hello, World!"
• Concatenation: Strings can be concatenated directly in code without a + operator; simply place them adjacent to each other.
<#include <stdio.h>>
int main() {
const char *str1 = "Hello, ";
const char *str2 = "World!";
const char *combined = "Hello, " "World!";
printf("String literal 1: %s\\n", str1);
printf("String literal 2: %s\\n", str2);
printf("Combined string literal: %s\\n", combined);
return 0;
}
String literal 1: Hello,
String literal 2: World!
Combined string literal: Hello, World!