Implicit Conversions and Narrowing Casts

Memory Usage

How do implicit conversions affect memory usage in my program?

3D art showing a wizard character

Understanding how conversions affect memory usage is important, especially in games where performance matters. Let's break this down:

Converting to Bigger Types

When you convert a smaller type to a bigger type, you use more memory:

#include <iostream>
using namespace std;

int main() {
  // Small number types
  char SmallNumber{65};          // Uses 1 byte
  int BiggerNumber{SmallNumber}; // Uses 4 bytes

  // The computer needs extra memory to
  // store the same value!
  cout << "Original char: " << SmallNumber;
  cout << "\nAs integer: " << BiggerNumber;
}
Original char: A
As integer: 65

Converting to Smaller Types

Going the other way can save memory but might lose information:

#include <iostream>
using namespace std;

int main() {
  // Big number type - uses 8 bytes
  double BigDecimal{3.14159265359};

  // Uses 4 bytes
  float SmallDecimal{
    static_cast<float>(BigDecimal)};

  cout.precision(10);
  cout << "Original:  " << BigDecimal << "\n";
  cout << "Converted: " << SmallDecimal;
}
Original:  3.141592654
Converted: 3.141592741

Memory Usage Guidelines

Here's what to remember about conversions and memory.

Converting to bigger types:

  • Always safe - no data loss
  • Uses more memory
  • Might be slightly slower

Converting to smaller types:

  • Might lose data
  • Uses less memory
  • Usually not worth the risk just to save memory

Most of the time, you should:

  1. Choose the right type for your data from the start
  2. Don't convert just to save memory unless you're sure you need to
  3. Use uniform initialization to catch accidental conversions that might lose data

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved