• Home
  • 1.19 Literals

1.19 Literals

View Categories

1.19 Literals

1 min read

Table of Contents

A literal is a fixed value written directly in the source code. C++ provides different types of literals to represent integers, floating-point values, characters, strings, and Boolean values.

This example demonstrates the declaration of variables using different literal types.

Source Code #

#include <iostream>

int main()
{
    int number = 100;
    double price = 99.95;
    char grade = 'A';
    const char message[] = "Hello";
    bool status = true;

    std::cout << "Integer: " << number << '\n';
    std::cout << "Floating Point: " << price << '\n';
    std::cout << "Character: " << grade << '\n';
    std::cout << "String: " << message << '\n';
    std::cout << "Boolean: " << status << '\n';

    return 0;
}

Output #

Integer: 100
Floating Point: 99.95
Character: A
String: Hello
Boolean: 1

Explanation #

  • 100 is an integer literal of type int.
  • 99.95 is a floating-point literal of type double.
  • 'A' is a character literal enclosed in single quotes.
  • "Hello" is a string literal enclosed in double quotes.
  • true is a Boolean literal representing the logical value true.
  • Each variable is initialized using a literal of the corresponding type.
  • std::cout displays the value stored in each variable.
  • Boolean values are printed as 1 for true and 0 for false unless std::boolalpha is enabled.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *