In C programming, literals are fixed values that are directly used in the source code. They represent constant values of various types such as integers, floating-point numbers, characters, and strings.
Literals are used to initialize variables, pass arguments to functions, or represent values directly in expressions.
Here are examples of different types of literals in C:
Literal values are used to initialize variables, pass arguments to functions, or represent values directly in expressions.
// Decimal integer literal int num1 = 123; // Base 10, no prefix // Hexadecimal integer literal int num2 = 0xAB; // Base 16, prefix with 0x or 0X // Octal integer literal int num3 = 057; // Base 8, prefix with 0 // Long integer literal int num4 = 123L; // Unsigned integer literal int num5 = 123U;
// Floating-point literal float num1 = 3.14; // Exponential notation (2.5 * 10^3) double num2 = 2.5e3; // Long double literal long double num3 = 1.2L;
// Character literal char ch1 = 'A'; // Newline character char ch2 = '\n'; // Tab character char ch3 = '\t'; // Backslash character char ch4 = '\\'; // Hexadecimal escape sequence ('A') char ch5 = '\x41';
Character literals represent single characters enclosed in single quotes.
char str1[] = "Hi, Welcome to C Tutorial!"; // String literal char str2[] = {'H', 'i', '\0'}; // String literal with array initialization
int boolVar1 = 0; // False int boolVar2 = 1; // True
String literals represent sequences of characters enclosed in double quotes (" "). String Literals are also stored as arrays of characters terminated by a null character '\0'.
// Null pointer literal int* ptr = NULL;
C Language does not have its built-in boolean type, but we can use integer literals `0` and `1` to represent `false` and `true`, respectively.
NULL is used to represent a null pointer, which is a pointer but, does not point to any memory location. It is often used to indicate that a pointer does not refer to a valid object or memory address.
Literals are used directly in the source code to represent fixed values of different types without the need for variables or expressions.