Guess = " "; Super important!

So Ben mentions that you need to initialize Guess to " " so that you know what’s being stored there. Well, that’s the reason why… but why? Really, truly why?

Here’s something I learned from the Harvard CS50 class through edX…

If you were to define guess like this:
string Guess;

What will happen is the computer will set aside a chunk of memory labeled “Guess” that is of size String. What’s the size of string? Well that’s irrelevant right now, but it’s the compiler’s dedicated size for storing a string. Not important.

What is important is that if you don’t tell the program WHAT to initially store at that memory block called Guess, then the values stored inside that memory may be whatever was using that block of memory last!

That could be a calculator app, YouTube browser tab, or your operating system… whoops!

We call this data “garbage values”.

So what this means is, if you were to ever try and access or modify Guess before anything is stored in it, you may accidentally access memory you shouldn’t, which can crash, break, corrupt, or BSOD other apps or your operating system.

So to ensure that you aren’t taking random pieces of memory that other programs require and storing / editing it inside of Guess, you instead first tell guess to store " ", or a blank string.

This way, you can ensure you always know what’s inside it and you’re not accessing parts of the operating system you shouldn’t.

And this is true for ANY variable type, not just strings. Initialize all your variables to something, anything. Just don’t leave them blank. This also serves a second purpose (setting default values).

This is incorrect.

T x;

This is known as default initialisation. For objects of class type (Guess would be an object of std::string which is a class) this calls the default constructor, for std::string this initialises it to an empty string. From cppreference:

  1. Default constructor. Constructs empty string (zero size and unspecified capacity). If no allocator is supplied, allocator is obtained from a default-constructed instance.

For primitive types this instead would initialise it to an indeterminate value. Reading an indeterminate value is undefined behaviour (UB). From the current working draft of the C++ Standard:

  1. undefined behavior
    behavior for which this document imposes no requirements
    [Note]: Undefined behavior may be expected when this document omits any explicit definition of behavior…cut

In a nutshell literally anything can happen when invoked. It’s commonly said that you could launch missiles somewhere.

Though realistically the most likely outcomes of invoking UB are:

  1. No observable effect.
  2. Works but with unexpected results.
  3. Works as expected.
  4. Program crashes.

Here’s an example of invoking UB where the compiler ends up calling a function that was never explicitly called by the program: https://godbolt.org/z/d9eCOh

1 Like

Privacy & Terms