Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can we use uninitialized variables in C++?

Tags:

c++

variables

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.

like image 536
unobatbayar Avatar asked Oct 24 '25 17:10

unobatbayar


2 Answers

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.

like image 92
Bathsheba Avatar answered Oct 26 '25 07:10

Bathsheba


It isn't feasible or even possible to detect or prove that variable is used uninitialized in all cases. For example:

int a;
if (<complex condition>)
    a = 0;
if (<another complex condition>)
    a = 1;
++a;

Can there be case when both conditions are false? You wouldn't know, unless you do an extensive analysis of your program. Pointers to variables can be passed, multithreading might be involved, making analysis even harder. So, the decision was made to trust the programmer and merely declare those UB.
Modern compilers can issue warnings in many cases of uninitialized variable usage, and you should always use maximum warning level.

like image 41
Revolver_Ocelot Avatar answered Oct 26 '25 06:10

Revolver_Ocelot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!