5 Types Of Literals In C & More Explained With Examples!
When writing programs in the C programming language, one frequently encounters various types of data that are used as constants or values within the code. These constants are known as literals. In C, they are specific values that are used directly in the program and are not represented by variables or expressions. Understanding literals in C is fundamental to programming the language, as they play a crucial role in specifying data values. In this article, we will delve into the different types of literals in C and how they are used.
Introduction To Literals In C
Literals are fixed values or constants used directly in the code to represent particular data types in C language. They are used to represent immutable, fixed values. Additionally, memory exists, even though pointers are not variables.
They are referred to as literals since they truly live out their own values. In C, literals can be used with integers, floating-point numbers, characters, strings, Boolean values, and other data types. The concept of literals in C is subject to the following requirements and rules:
- Rules of syntax: Literals must abide by the syntactic requirements specified for each form of data. For instance, floating-point literals should have a decimal point and/or an exponent portion, whereas integer literals shouldn't have either.
- Limitations on data types: Literal values shouldn't be larger than the data type's range or precision. For instance, the range of an integer literal allocated to a short int data type should not be exceeded.
- Type compatibility: It's crucial to check that the literal value matches the anticipated data type before using it in expressions or assignments. Mismatched types might result in compilation issues or unexpected behavior.
- Escape sequences: Some characters must be enclosed in backslashes in order to represent special characters in character and string literals. For instance, the letters n and t stand for newline and tab, respectively.
- String's conclusion: In C, string literals are null-terminated, which means they have a '0' at the end to denote the end of the string. It is necessary to properly end string literals in order to avoid accessing the wrong memory addresses.
- Depending on the data type and any given sign when using them, integer literals can be either signed or unsigned. For example, signed integer literals without signs are interpreted as such, but unsigned literals are believed to be those that end in u or U.
- Built-in Boolean literals are not supported in C. Instead, boolean values are frequently represented by integers, with 0 representing false and any value other than zero denoting true. When handling boolean expressions and assignments, this convention should be followed.
Types Of Literals In C
The categories of literals in C are shown in the following table:
Literal Type |
Example |
Description |
Integer Literals |
123 |
Whole numbers without decimal points |
Floating-Point Literals |
3.14 |
Numbers with decimal points |
Character Literals |
M |
Single characters enclosed in single quotes |
String Literals |
“Unstop” |
Sequences of characters enclosed in double quotes |
Boolean Literals |
0 (false) |
Representing logical true or false values |
Integer Literals In C
Integer literals can consist of a decimal, octal, or hexadecimal constant.
- The base or radix for these is specified by a prefix, which can be 0 for hexadecimal, 0 for octal, or nothing for decimal.
- Another possible suffix for an integer literal is a combination of the letters U and L, which stand for unsigned integer and long, respectively.
- Also, the suffix can be in any order and either capital or lowercase letters.
a. Decimal Integer Literal
- They consist of digits from 0 to 9.
- The first digit must not be 0.
- e.g., 91, 900, and 100 are valid decimal constants.
- e.g., 091, 009, and 0100 are invalid decimal constants.
b. Octal Integer Literal
- They consist of digits from 0 to 7.
- The first digit must be 0.
- e.g., 017, 0100, and 016 are valid octal constants.
- e.g., 019, 018, and 150 are invalid octal constants.
c. Hexadecimal Integer Literal
- They consist of digits from 0 to 9,10(A),11(B),12(C),13(D),14(E), and15(F).
- The first two characters must be 0x or 0X. (Zero X).
- e.g., 0x60, 0x1AB, and 0x10A are valid hexadecimal constants
- e.g., 0xx60, 01AB, and 0x10G are invalid hexadecimal constants
Code Example to Demonstrate Use of Different Integer Literals in C
Output:
Decimal: 123
Octal: 123
Hexadecimal: 1A
Sum: 206
Difference: -97
Explanation:
In the above code example,
- We have first declared three variables in the int main() function.
- These are decimal, octal, and hexadecimal, which we initialize with the values of 123, 0123, and 0x1A, respectively.
- We then use the addition operator (+) to add the variables decimal and octal and store the result in the variable sum.
- Next, we use the subtract operator (-) to subtract decimal from hexadecimal and store the result in the variable difference.
- Finally, we use the printf() function to print the literal values and the results of operations.
Note - Here, we used the %d specifier for decimal, the %o specifier for octal, the %X for hexadecimal, and \n for a new line, i.e., printing the result in the next line.
Floating-Point Literals In C
Floating-point literals are those that have both an integer part and a decimal part. In other words, it has an integer and can have an exponential, fractional, or decimal part. They have two forms in which we can represent them, namely- decimal form and exponential form.
a. Decimal Form Floating-Point Literals
The decimal floating-point literal can either have an exponential part, or a decimal part, or both. In other words, a decimal form floating-point literal consists of a sequence of digits, optionally followed by a decimal point.
- Example: 3.14
- By default, decimal form floating-point literals are of type double.
- It can be assigned to variables of type double, long double, or float.
b. Exponential Form Floating-Point Literals
The exponential floating-point literal consists of an integer part, a fraction part, or can even have both. Also, the syntax of the exponential form literal consists of a sequence of digits, followed by the letter 'e' or 'E', and then an exponent value (integer).
- Example: 6.022e23
- The 'e' or 'E' indicates the exponent part of the literal.
- The value before the 'e' or 'E' represents the significant, and the value after it represents the exponent.
- Exponential form floating-point literals are also of type double by default.
- It can be assigned to variables of type double, long double, or float.
Code Example to Demonstrate the Usage of Different Floating-point Literals in C
Output:
Decimal Float: 3.140000
Decimal Double: 3.140000
Decimal Long Double: 3.140000
Exponential Float: 602200013124147498450944.000000
Exponential Double: 602200000000000027262976.000000
Exponential Long Double: 602200000000000000000000.000000
Explanation:
- The code begins by including the necessary header file stdio.h for input/output operations in C.
- Then, we define the main() function, which is the entry point of the program.
- We declare different types of floating-point literals in the main and initialize them, as mentioned in the code comments. They are-
- decimalFloat is a float variable initialized with the decimal form floating-point literal 3.14f.
- decimalDouble is a double variable initialized with the decimal form floating-point literal 3.14.
- decimalLongDouble is a long double variable initialized with the decimal form floating-point literal 3.14L.
- exponentialFloat is a float variable initialized with the exponential form floating-point literal 6.022e23f.
- exponentialDouble is a double variable initialized with the exponential form floating-point literal 6.022e23.
- exponentialLongDouble is a long double variable initialized with the exponential form floating-point literal 6.022e23L.
- The values of the floating-point literals are printed using the printf() function:
- %f is used as the format specifier for printing float variables.
- %lf is used as the format specifier for printing double variables.
- %Lf is used as the format specifier for printing long double variables.
- The program ends with the return 0 statement, indicating successful execution.
Also read- C Program To Reverse A Number | 6 Ways Explained With Examples
Character Literals In C
Character literals represent individual characters in C programming and are denoted using single quotation marks.
- Variables of the char data type can receive character literal assignments. Some examples of character literals in C include 'U','m',‘8’ or '@'.
- Character literals are also used to represent the ASCII character set in C. One may derive the ASCII value of a character literal using the appropriate decimal number.
- The initialization of character arrays, character comparisons, and character-based operations are just a few situations where character literals might be useful.
- The %c format specifier is utilized for printing character literals using printf or other equivalent methods.
- Character literals differ from string literals in that the latter is expressed by a string of characters encased in double quotation marks ("_").
- In C programming, character literals let you manipulate and interact with specific characters individually.
Code Example to Showcase the Usage of Character Literals in C
Output:
The first letter is: A
The second letter is: B
The digit is: 7
The ASCII value of A + 1 is: 66
The difference between B and 'A' is: 1
Explanation:
- We begin the C program above by including the needed header files and then define the main() function.
- Inside main(), we define three char type variables, i.e., letter1, letter2, and digit, and initialize them with character literal values A, B, and 7, respectively.
- We then use the printf() function, with %c format specifier, to print the values of the character variables.
- Next, we carry out a few operations on these character variables as follows-
- The ASCII value of letter1 is increased by 1, and the output is stored in result1 (i.e., int result1 = letter 1 + 1). The outcome will be 66 since A has an ASCII value of 65.
- Similarly, we deduct the ASCII value of letter2 from the ASCII value of A (i.e., int result2 = letter2 - 'A').
- Finally, we use printf() and proper format specifiers to display the outcomes of these operations.
Multi-char Literals In C
For C, character literals come in the char, string, unicode, and raw types. Additionally, there is a multi-character literal with multiple c-chars. A multi-character literal is conditionally supported, has the type int, and has a value determined by the implementation, whereas a single c-char literal has the type char.
- The syntax of a multi-character literal is a sequence of characters enclosed in single quotes (''). For example: 'ABCD'
- The behavior and interpretation of multi-character literals are implementation-defined values.
- The order of characters in the literal may depend on the platform's endianness.
- Multi-character literals are typically used for special purposes, such as creating implementation-specific codes or flags.
Code Example to Showcase the Usage of Multi-character Literals in C
Output:
Multi-Character Literal: 1094861636
Explanation:
- In this example, we declare an int variable called multiChar and assign the multi-character literal 'ABCD' to it.
- We use the printf() function with the %d format specifier to print the value of multiChar.
- The output displays the implementation-defined integer value of the multi-character literal assigned to multiChar.
- It's important to note that this value can vary depending on the platform and compiler being used.
Note- The use of multi-character literals is not recommended, as their behavior is implementation-defined and can lead to portability issues. It's best to avoid relying on the specific integer values assigned to multi-character literals.
String Literals In C
String literals represent sequences of characters enclosed in double quotes (""). They are used to represent text or character sequences.
- The syntax for a string literal consists of a sequence of characters enclosed in double quotes ("_"). For example: "Hey, User!"
- The end of a string literal is automatically denoted by the null character ('0') since string literals are null-terminated.
- The characters contained in the string literal can be escape sequences, special characters, or alphanumeric characters.
- Similar to character literals, escape sequences can be used to express special characters or control sequences within a string.
- A string literal size consists of the string's whole character set plus one extra byte for the null character.
Code Example to Demonstrate the Usage of String Literals in C
Output:
Greeting: Hello, World!
Explanation:
- We declare a character array named greeting and initialize it with the string literal "Hello, World!", inside the main() function. The string literal represents the text we want to store in the array.
- Then, we use the printf() function to display the contents of the greeting array. The format specifier %s indicates that we want to print a string.
- The value of greeting is substituted into the %s placeholder, resulting in the output as shown above.
- Finally, return 0 ends the main() function and returns the value 0 to indicate successful program execution.
Boolean Literals In C
The truth values of logical expressions are represented using boolean literals. Though boolean literals are commonly represented using integer values, where 0 represents false and any non-zero value represents true, the C programming language does not come with a built-in boolean data type.
- Syntax: Boolean literals are represented using integer values, where 0 represents false and any non-zero value represents true. For example: 0 (false), 1 (true)
- Boolean literals are frequently used in logical operations and conditional expressions to establish the truth value for conditions.
- Integers are frequently used to represent boolean values since C lacks a specific data type for booleans.
- It's crucial to remember that any non-zero value (not simply one) is taken into consideration to be true. Any non-zero value may be used instead of the standard true value of 1, which equals 1.
Code Example to Demonstrate the Usage of Boolean Literals in C
Output:
Is it raining? 1
Is it sunny? 0
Explanation:
- We declare two integer variables isRaining and isSunny, in the main() function and initialize them with boolean literals.
- In C, boolean literals are represented using integers, where 0 represents false and any non-zero value represents true. Here, isRaining is initialized with 1 (representing true), and isSunny is initialized with 0 (representing false).
- Then, we use the printf() function with the %d format specifier to display these boolean literals.
- The value of isRaining is substituted into the %d placeholder in the first printf statement.
- And the value of isSunny is substituted into the %d placeholder in the second printf statement.
Decimal Notation
The base-10 system, also referred to as decimal notation, uses ten symbols (0–9) to represent numbers and is a positional numeral system. The place value or position of each digit in a decimal number determines its value. In C, decimal notation is the default representation for integers.
Code Example to Demonstrate Decimal Notation in C
Output:
12345
Explanation:
- The code begins by including the standard input/output library (<stdio.h>) to use the printf function.
- Then, in the main() function, we declare and initialize an integer variable called number with the value 12345.
- Next, we use the %d format specifier (which stands for a decimal integer) and the printf() function to display the value on the console.
Exponential Notation
Scientific notation, also commonly referred to as exponential notation, is a condensed and uniform approach to expressing very large or very small numbers.
- It expresses a number as the product of a coefficient and a power of 10.
- The power of 10 denotes how many places the decimal point should be shifted, and the coefficient is normally a decimal number more than or equal to 1 and less than 10.
- Although there is no built-in data type for the exponential notation in C, you can show numbers in scientific notation by using the printf function's %e format specifier.
Code Example to Demonstrate Exponential Notation in C
Output:
1.234568e+08
Explanation of the code:
In the code example above-
- Inside the main() function, we declare a double variable called number and initialize it with the value 123456789.0.
- Then using the printf() function with the %e format specifier (which represents a double value in exponential notation), we display the value of a number to the console.
- The output is displayed on the console as 1.234568e+08, where e+08 indicates the power of 10 to move the decimal point by 8 places to the right.
Rules For Representation Of Real Constants In Exponential Notation
There are a few guidelines to remember when expressing real constants in exponential notation. The main guidelines are as follows:
- The coefficient must have a decimal value that is higher than or equal to 1 and less than 10. It stands for the number's significant digits.
- Exponent: The exponent denotes the power of 10 that should be used to multiply the coefficient. It might be favorable or unfavorable.
- Format: The most common format for exponential notation is a × 10^b or aE±b, where a is the coefficient and b is the exponent. The ± sign indicates whether the exponent is positive or negative.
- Since it is commonly used in the sciences and engineering to represent extremely large or small numbers, exponential notation is also known as scientific notation.
Following are a few examples of real constants represented in exponential notation-
6.022 × 10^23 (Avogadro's number)
3.14159 × 10^0 (pi)
1.602E-19 (elementary charge)
When using real constants in programming languages like C, you can display integers in exponential notation using the proper format specifier in output functions like printf, such as %e or %E.
Constants In C
Constants are values that remain constant during the course of a program. Once a value is assigned to them, it cannot be modified, i.e., it becomes fixed. Constants are used to represent stable, unchanging values, such as mathematical constants, physical constants, and other variables that shouldn't be changed.
There are various sorts of constants in C, each with a unique syntax and application. Here are some typical C constant types:
Integer Constants: These are entirely integral without any fractional portions. The formats in which they can be expressed are non-zero decimal digits, octal (base 8), and hexadecimal characters (base 16). For example:
Decimal: 42
Octal: 052 (starts with 0)
Hexadecimal: 0x2A or 0X2A (starts with 0x or 0X)
Floating-Point Constants: Real values with fractional components are represented by floating-point constants. They can be expressed in exponential or hexadecimal notation. For example:
Decimal: 3.14 or 42.0
Exponential: 1.5e-3 or 6.02e23
Character Constants: Individual characters that are encapsulated in single quotations are represented by character constants. For example:
'A'
'9'
'\n' (newline character)
String Constants: A string constant is a group of characters that are double-quoted. For example:
"Hey, User!"
"Microsoft"
Enumeration Constants: These are user-defined constants that represent a collection of named integer values. The keyword "enum" is used to construct them. For example:
enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER};
Code Example to Demonstrate Use of Constants in C
Output:
Integer Constant: 42
Floating-Point Constant: 3.140000
Character Constant: A
String Constant: Hello, World!
Enumeration Constant: 1
Explanation :
- We begin by including the standard input/output file and then define the main() function (the entry point of the program, which returns an integer value 0).
-
Inside the main, we declare and initialize four constant variables of different data types as follows:
- An integer constant named INTEGER_CONSTANT with a value of 42.
- A double-precision floating-point constant named FLOATING_CONSTANT with a value of 3.14.
- A character constant named CHARACTER_CONSTANT with the character 'A'.
- A string constant named STRING_CONSTANT containing the text "Hello, World!".
- An enumeration type called Month containing twelve constants (representing months) from JANUARY to DECEMBER. Here, each constant is assigned an integer value automatically, starting from 0 for JANUARY and incrementing by 1 for each subsequent month.
- Next, we use the printf() function along with appropriate format specifiers to display the values of these constants and the FEBRUARY enumeration constant.
- The program ends by returning 0 from the main function, indicating successful execution.
Read more here- Constant In C | How To Define & Its Types Explained With Examples
Difference Between Literals & Constants In C
Literals |
Constants |
|
Definition |
Literal values are fixed values directly written in the code. |
Constants are named values that are declared and assigned fixed values. |
Mutability |
Literals cannot be modified or changed. |
Constants cannot be modified once they are assigned a value. |
Usage |
Literals are used directly in expressions or assignments. |
Constants are used to represent fixed and unchanging values in the program. |
Syntax |
Literals have a specific syntax based on their type. |
Constants are declared using the const keyword followed by a data type. |
Examples |
42 (integer literal), 3.14 (floating-point literal) |
const int MAX_VALUE = 100; |
Conclusion
Literals are fundamental to C programming, providing a way to represent constant values in your code. They serve as essential tools for initializing variables, declaring constants, and enhancing code readability. There are five primary types of literals, including integer literals, string literals, floating-points, characters, and boolean literals. Understanding the different types of literals and when to use them is crucial for writing efficient and maintainable C programs. By harnessing the power of literals, you can create code that is not only robust but also easy to understand and maintain, which is a hallmark of good programming practice.
Also read- 100+ Top C Interview Questions With Answers (2023)
Frequently Asked Questions
Q. Does a literal in C refer to a string or character?
Depending on the context, a literal in C can refer to either strings or characters.
- String literals are a series of characters contained in double quotation marks. An example of a string literal is "Hey, User!"
- A single character wrapped in single quotation marks is referred to as a character literal or character constant. For example, 'M'.
The presence of single quotes for character literals and double quotes for string literals helps to distinguish between the two, even though a literal can represent both strings and characters.
Q. What is the size of the character literal in C?
In single quotes, a character literal, such as 'A' or '7', denotes a single character. In the C programming language, a character has a fixed size of 1 byte or 8 bits. Therefore, the size of a character literal in C is 1 byte.
- The char data type, which includes character literals, has a size guarantee of 1 byte per the C standard.
- A large selection of characters from the ASCII character set and other character encoding methods can be represented at this size.
- It's important to remember that a character's literal size is constant regardless of the actual character it represents.
All character literals in C are regarded as 1 byte in size, regardless of whether they are an alphabet letter, a numeric, a special character, or an escape sequence.
Q. Can a literal in C be a string?
Yes, a literal can be a string. More specifically, a string literal in programming is a group of characters encased in double-quotes. It represents a fixed, immutable string value within the source code.
- In C and comparable programming languages, string literals are frequently used to represent text-based data, including messages, names, and other character sequences.
- They are immutable, which means that once their contents have been declared in code, they cannot be changed.
- String literals in C are inherently null-terminated, which is an important distinction to make. This signifies that the string is automatically terminated by appending the null character ('0') at the end.
Q. Are character and string the same?
No, a character and a string are not the same. A character (char) in the language of C stands for a single character, such as a letter, number, or symbol. It is a basic data type, generally taking up 1 byte of memory.
A string, on the other hand, is a collection of characters. It is shown as a character array finished by the null character ('0'). Strings are implemented as character arrays in the C language.
Also, we use single quotes to contain characters (e.g., 'M', '8', and 'n'), whereas we use double quotes to enclose strings (for e.g., "Hello" and "Unstop").
Q. What is a string literal vs. a string?
A string literal is a constant value made up of sequence of characters used directly in the source code, and it represents a predetermined string of characters. We use double quotes to contain the characters that make up a string literal. For example, "Hello, World!". The string literals cannot be changed and have a known length. String variables are frequently initialized or given values using string literals.
On the other hand, string is a data type representing a series (or an array) of that is terminated by the null character ('0') in C. A string is implemented in C as an array of characters, with a null character as the last character to signify the string's conclusion. During program execution, string variables can be changed and can store various character sequences.
Q. What is a char array in C?
A char array is a data structure used in the C programming language that represents a collection of characters kept in a row of dynamic memory locations. Since raw strings are simply character arrays, there is a mechanism to store and manipulate strings in the C programming language.
The data type char is specified before square brackets [], which denote the array's size, to declare a char array. The syntax to declare a char array is as follows:
char arrayName[size];
The size parameter determines how many elements (characters) the array can carry, and the arrayName identifier represents the name of the char array. The length of the entire string that can be stored, including the null character ('0') at the end, depends on the size of the char array.
Q. What is a literal type?
A literal type in programming languages such as C and C++ is a type whose values can be written as literals directly in the source code. In other words, a literal type enables you to directly represent constant values in your code without the need for calculations or expressions.
Literal types are frequently simple data types like booleans, normal characters, constant integers, and floating-point numbers. These types have a clear syntax that allows their values to be written directly as literals in C source code.
You might also be interested in reading the following: