Welcome to our lesson on C++ Literals! In this tutorial, we'll dive into understanding what literals are, why they are essential, and how to use them in your C++ programs. Let's get started!
In simple terms, literals are specific values that are used to initialize variables or constants in a program. In C++, there are various types of literals, each representing different data types like integers, floating-point numbers, characters, and strings.
An integer literal is a sequence of digits representing an integer number. Here are some examples:
int myNum = 123; // decimal integer
int anotherNum = 0xABCD; // hexadecimal integer
int yetAnotherNum = 0123; // octal integerš Note: When using hexadecimal or octal numbers, you must start the literal with 0x or 0, respectively.
Floating-point literals represent decimal numbers with a fractional part. Here are some examples:
float pi = 3.14159; // decimal floating-point
double piValue = 3.14159265358979323846; // double precision floating-pointš Note: When initializing a float variable, use the float keyword. For double precision floating-point, simply omit the keyword.
Character literals represent individual characters. In C++, character literals are enclosed in single quotes. Here's an example:
char myChar = 'A';š Note: Character literals can also represent ASCII codes using their decimal values, like so:
char myCharCode = 65; // ASCII code for 'A'String literals represent a sequence of characters, enclosed in double quotes. Here's an example:
std::string myString = "Hello, World!";š Note: To create a multi-line string, enclose the string in triple double quotes.
Which of the following is a valid character literal representing the ASCII code for 'A'?
Now that you have a basic understanding of literals, let's move on to some practical examples.
#include <iostream>
int main() {
int myNum = 123;
int anotherNum = 0xABCD;
int yetAnotherNum = 0123;
std::cout << "Dec: " << myNum << std::endl;
std::cout << "Hex: " << anotherNum << std::endl;
std::cout << "Oct: " << yetAnotherNum << std::endl;
return 0;
}#include <iostream>
int main() {
float pi = 3.14159;
double piValue = 3.14159265358979323846;
std::cout << "Pi (float): " << pi << std::endl;
std::cout << "Pi (double): " << piValue << std::endl;
return 0;
}#include <iostream>
int main() {
char myChar = 'A';
char myCharCode = 65;
std::cout << "Char: " << myChar << std::endl;
std::cout << "Code: " << myCharCode << std::endl;
return 0;
}#include <iostream>
#include <string>
int main() {
std::string myString = "Hello, World!";
std::string multiLineString = R"(
This is a multi-line string
with multiple lines.
)";
std::cout << "String: " << myString << std::endl;
std::cout << "Multi-line: " << multiLineString << std::endl;
return 0;
}That's it for today! With these examples, you should now have a solid understanding of literals in C++. In the next lesson, we'll dive into variables and data types.
Stay tuned! šÆ