Search code examples
c++variables

Why can we use uninitialized variables in C++?


In programming languages like Java, C# or PHP we can't use uninitialized variables. This makes sense to me.

C++ dot com states that uninitialized variables have an undetermined value until they are assigned a value for the first time. But for integer case it's 0?

I've noticed we can use it without initializing and the compiler shows no error and the code is executed.

Example:

#include <iostream>
using namespace std;

int main()
{
    int a;
    char b;
   
    a++; // This works... No error
    cout<< a << endl; // Outputs 1
 
    // This is false but also no error...
    if(b == '0'){
      cout << "equals" << endl;
    }
 
    return 0;
}

If I tried to replicate above code in other languages like C#, it gives me compilation error. I can't find anything in the official documentation.

I highly value your help.


Solution

  • C++ gives you the ability to shoot yourself in the foot.

    Initialising an integral type variable to 0 is a machine instruction typically of the form

    REG XOR REG
    

    Its presence is less than satisfactory if you want to initialise it to something else. That's abhorrent to a language that prides itself on being the fastest. Your assertion that integers are initialised to zero is not correct.

    The behaviour of using an uninitialised variable in C++ is undefined.