C++ Literals

Hi everyone, inside this article we will see about C++ Literals.

In C++, literals are fixed values that are assigned to variables. There are several types of literals in C++, including integer literals, floating-point literals, character literals, string literals, and boolean literals.

Types of Literals

Integer literals: An integer literal is a sequence of digits that represents a whole number. For example: 123, -456. Integer literals can be specified in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation. For example: 0xA1 (hexadecimal), 011 (octal).

Floating-point literals: A floating-point literal is a number that contains a decimal point or an exponent. For example: 3.14, 1.23e+5.

Character literals: A character literal is a single character enclosed in single quotes. For example: 'A', 'a'.

String literals: A string literal is a sequence of characters enclosed in double quotes. For example: "Hello World".

Boolean literals: There are two boolean literals in C++: true and false.

In C++, it’s important to use the appropriate literal type for your variables. Using the wrong type can result in unexpected behavior or errors in your program.

You can use C++ literals by assigning them to variables. For example:

int x = 123;
float y = 3.14;
char z = 'A';
string s = "Hello World";
bool b = true;

Here, the integer literal 123 is assigned to the integer variable x, the floating-point literal 3.14 is assigned to the floating-point variable y, the character literal 'A' is assigned to the character variable z, the string literal "Hello World" is assigned to the string variable s, and the boolean literal true is assigned to the boolean variable b.

It’s important to use the appropriate literal type for your variables. For example, if you need to store a whole number, you should use an integer literal and assign it to an int variable. If you need to store a character, you should use a character literal and assign it to a char variable. And so on.

cout << 123 << endl;
cout << 3.14 << endl;
cout << 'A' << endl;
cout << "Hello World" << endl;
cout << true << endl;

Here, the literals are used directly as arguments to the cout statement, which outputs them to the console.

We hope this article helped you to understand about C++ Literals in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.