Literals in C
In C programming, literals are fixed values that are directly assigned to variables. They are also referred to as constants and can be of various types such as integer, floating-point, character, or string literals.
Types of Literals
- Integer Literals: Whole numbers without any fractional part.
- Floating-point Literals: Numbers with a fractional part or in exponential notation.
- Character Literals: A single character enclosed in single quotes.
- String Literals: A sequence of characters enclosed in double quotes.
- Boolean Literals: Represents
true
orfalse
.
Examples of Literals
Integer Literals
#include <stdio.h>
int main()
{
int age = 25; // Decimal literal
int oct = 031; // Octal literal
int hex = 0x19; // Hexadecimal literal
printf("Decimal: %d\n", age);
printf("Octal: %o\n", oct);
printf("Hexadecimal: %x\n", hex);
return 0;
}
Output
Decimal: 25
Octal: 31
Hexadecimal: 19
Octal: 31
Hexadecimal: 19
Floating-point Literals
#include <stdio.h>
int main()
{
float pi = 3.14; // Regular floating-point literal
double exp = 2.1e3; // Exponential form
printf("Value of pi: %f\n", pi);
printf("Exponential form: %e\n", exp);
return 0;
}
Output
Value of pi: 3.140000
Exponential form: 2.100000e+03
Exponential form: 2.100000e+03
Character Literals
#include <stdio.h>
int main()
{
char grade = 'A'; // Character literal
printf("Grade: %c\n", grade);
return 0;
}
Output
Grade: A
String Literals
#include <stdio.h>
int main()
{
char message[] = "Hello, World!"; // String literal
printf("Message: %s\n", message);
return 0;
}
Output
Message: Hello, World!