C++ Constants/Literals

Hello there, future programmers! Today, we're going to embark on an exciting journey into the world of C++ constants and literals. Don't worry if these terms sound a bit intimidating – by the end of this lesson, you'll be throwing them around like a pro! Let's dive in!

C++ Constants/Literals

What are Constants and Literals?

Before we get into the nitty-gritty, let's understand what constants and literals are. Think of them as the "unchangeable" elements in your code – like the number of days in a week or the value of pi. They're the reliable friends who always stay the same, no matter what's happening in your program.

Integer Literals

Let's start with something familiar – numbers! In C++, when we write a whole number directly in our code, we call it an integer literal. It's like writing a number on a piece of paper – simple and straightforward.

int myAge = 25;
int numberOfPlanets = 8;
int negativeNumber = -10;

In these examples, 25, 8, and -10 are integer literals. They're just sitting there, being numbers, without any decimal points or fancy stuff.

But wait, there's more! C++ allows us to write integer literals in different number systems:

int decimalNumber = 42;     // Decimal (base 10)
int octalNumber = 052;      // Octal (base 8) - starts with 0
int hexNumber = 0x2A;       // Hexadecimal (base 16) - starts with 0x
int binaryNumber = 0b101010;// Binary (base 2) - starts with 0b (C++14 onwards)

Don't worry if octal, hexadecimal, or binary seem confusing. For now, just know that they're different ways to represent the same number. It's like speaking different languages – "forty-two", "cuarenta y dos", and "quarante-deux" all mean the same thing!

Floating-point Literals

Now, let's add some decimal points to the mix! Floating-point literals are numbers with decimal points or in scientific notation.

float pi = 3.14159f;
double avogadroNumber = 6.022e23;
long double veryPreciseNumber = 1.23456789L;

Here, 3.14159f is a float literal (note the 'f' at the end), 6.022e23 is a double literal in scientific notation (e23 means ×10^23), and 1.23456789L is a long double literal (note the 'L' at the end).

Boolean Literals

Boolean literals are the simplest of all – there are only two!

bool isAwesome = true;
bool isBoring = false;

That's it! Just true and false. They're like the "yes" and "no" of the programming world.

Character Literals

Character literals represent single characters and are enclosed in single quotes.

char firstInitial = 'J';
char newline = '\n';
char tab = '\t';

The last two examples show special characters: '\n' for a new line and '\t' for a tab. These are called escape sequences.

String Literals

String literals are sequences of characters enclosed in double quotes.

std::string greeting = "Hello, World!";
std::string quote = "To be, or not to be, that is the question.";

Remember, strings use double quotes, while single characters use single quotes!

Defining Constants

Now that we know about literals, let's see how we can use them to create constants – values that don't change throughout our program.

The #define Preprocessor

One way to define constants is using the #define preprocessor directive:

#define PI 3.14159
#define MAX_STUDENTS 30

// Usage
double circleArea = PI * radius * radius;
if (numberOfStudents > MAX_STUDENTS) {
    std::cout << "Class is full!";
}

The #define directive tells the compiler to replace every occurrence of PI with 3.14159 and MAX_STUDENTS with 30 before compiling the code.

The const Keyword

A more modern and preferred way to define constants is using the const keyword:

const double PI = 3.14159;
const int MAX_STUDENTS = 30;

// Usage is the same as with #define

The const keyword tells the compiler that these variables cannot be changed after initialization.

Putting It All Together

Let's wrap up with a little program that uses various constants and literals:

#include <iostream>
#include <string>

#define GAME_NAME "C++ Adventure"

int main() {
    const int MAX_LEVEL = 100;
    const double XP_MULTIPLIER = 1.5;

    int currentLevel = 1;
    double currentXP = 0.0;
    bool hasCompletedTutorial = false;
    char playerRank = 'D';
    std::string playerName = "Newbie";

    std::cout << "Welcome to " << GAME_NAME << "!" << std::endl;
    std::cout << "Player: " << playerName << std::endl;
    std::cout << "Level: " << currentLevel << "/" << MAX_LEVEL << std::endl;
    std::cout << "XP: " << currentXP << std::endl;
    std::cout << "Rank: " << playerRank << std::endl;
    std::cout << "Tutorial completed: " << (hasCompletedTutorial ? "Yes" : "No") << std::endl;

    return 0;
}

This program uses all the types of constants and literals we've discussed. It defines a game name using #define, sets a maximum level and XP multiplier using const, and uses various literals to initialize the player's stats.

Conclusion

Congratulations! You've just taken your first steps into the world of C++ constants and literals. Remember, these are the building blocks of your programs – the unchanging values that you'll use to create amazing things. As you continue your programming journey, you'll find yourself using these concepts every day. Keep practicing, stay curious, and happy coding!

Literal Type Example Description
Integer 42, -10, 0, 1000 Whole numbers
Octal 052, 077 Base-8 numbers (start with 0)
Hexadecimal 0x2A, 0xFF Base-16 numbers (start with 0x)
Binary 0b101010 Base-2 numbers (start with 0b, C++14 onwards)
Floating-point 3.14, 2.5f, 1e10 Numbers with decimal points or in scientific notation
Boolean true, false Logical values
Character 'A', '\n', '\t' Single characters or escape sequences
String "Hello", "C++" Sequences of characters

Credits: Image by storyset