Skip to Content
Course content

7: Variables, Types, and References

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why can't I just use one type for all numbers?

Coming from languages like Python or JavaScript, C++'s insistence on int, float, double, and long feels like unnecessary bookkeeping. But here's the thing: C++ is designed to give you direct control over how much memory your program consumes. Every byte counts when you're writing high-performance code.

Think of it like choosing a storage container. If you're storing the number of lives a player has in a game, an int is perfect. You'll never have 3.5 lives. But if you're calculating the trajectory of a projectile or the precise coordinates of a character in a 3D space, an int will chop off all your decimals (truncation), and your character will just teleport in jagged jumps. That's where double comes in.

int lives = 3; 
double healthPercentage = 94.2;
bool isGameOver = false;

// If I try to put 94.2 into an int, C++ just throws the .2 away.
int brokenHealth = healthPercentage; // brokenHealth is now 94

I usually default to double for decimals because modern hardware handles it efficiently, and float is mostly reserved for specific cases like GPU programming or massive arrays where memory is extremely tight.

What exactly is a reference, and why not just copy the variable?

This is where a lot of learners get tripped up. A reference is essentially a "nickname" or an alias for an existing variable. When you create a reference using the & symbol, you aren't creating a new piece of data; you're just creating a new way to talk to the same spot in memory.

Imagine you have a massive object—like a 3D model of a city with thousands of coordinates. If you pass that object into a function to change its color, C++'s default behavior is to copy the entire city. That's a massive waste of CPU and RAM. By using a reference, you're telling the function, "Don't make a copy; just go to this specific address and change the original."

void applyDamage(int& currentHealth, int damage) {
    currentHealth -= damage; // This modifies the actual variable passed in
}

int main() {
    int playerHP = 100;
    applyDamage(playerHP, 20); 
    // playerHP is now 80 because we passed it by reference
}

If I had removed that & from the function signature, the function would have created a local copy of playerHP, subtracted 20 from the copy, and then deleted that copy when the function ended. The original playerHP would have stayed at 100, and you'd be wondering why your enemies aren't doing any damage.

Does it actually matter if I initialize a variable immediately?

In short: yes, it matters immensely. In some languages, an uninitialized variable defaults to 0 or null. In C++, it contains "garbage data"—whatever random bits happened to be left over in that memory address by the last program that used it.

I've seen veteran devs waste hours debugging a "random" bug only to realize they declared int score; without setting it to 0, and the program started the game with the player having -1,294,832,102 points. It's a nasty habit that leads to non-deterministic bugs (bugs that only happen sometimes).

int a = 0;       // Safe. Initialized.
int b;            // Dangerous. Contains "garbage" value.
int c{10};        // Also safe. This is "uniform initialization" (C++11 and later).

I highly recommend using the { } syntax (uniform initialization). Not only is it consistent across all types, but it also prevents "narrowing conversions"—meaning the compiler will yell at you if you try to accidentally cram a double into an int.




📋 Practical Task

Exercise: Building a Character Stat Modifier

Your task is to create a small program that manages a character's attributes. You need to demonstrate your understanding of different types and the use of references to modify data.

  • Create an int for level, a double for experiencePoints, and a bool for isAlive.
  • Write a function called gainExperience that takes the experience variable by reference and adds a specific amount to it.
  • Write a second function called levelUp that takes the level variable by reference and increments it by 1.
  • In your main function, initialize your character, call the experience function, and then call the level-up function.
  • Print the final stats to the console to verify that the original variables were actually modified.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.