0

I have the following function:

int main()
{
    int local_int;
    std::cout << local_int << std::endl;
    return 0;
}

which prints 0.

But the next function:

int main()
{
    int local_int;
    std::string local_str;
    std::cout << local_int << std::endl;
    std::cout << local_str << std::endl;
    return 0;
}

prints

21930

(the second line is the empty string)

Can someone help me understand what is going on between the two functions and why local_int isn't zero in the second function?

mehsheenman
  • 522
  • 4
  • 11

1 Answers1

3

Your title mentions an initialised int, but it really is not.

The declaration int local_int; (where you have it(1) in the source code) declares an uninitialised integer which may have any arbitrary value, it's as legal for it the be 314159 as it is to be zero.

If you want it to have a specific value, simply initialise it with something like:

int local_int = 42;

(1) This is because it is automatic storage duration. If it had a different storage duration, it would follow different rules and may be default- or zero-initialised. But that is not the case with this simple non-static int declaration within a function.

More information on the different storage durations, and how they are initialised (or not), are covered in the ISO C++ standard in excruciating detail :-)

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953