Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What benefit is there of allowing a variable to be left uninitialized?

In many languages you're allowed to declare a variable and use it before initializing it.

For example, in C++, you can write a snippet such as:

int x;
cout << x;

This would of course return unpredictable (well, unless you knew how your program was mapping out memory) results, but my question is, why is this behavior allowed by compilers?

Is there some application for or efficiency that results from allowing the use of uninitialized memory?

edit: It occurred to me that leaving initialization up to the user would minimize writes for memory mediums that have limited lifespans (write-cycles). Just a specific example under the aforementioned heading of 'performance'. Thanks.

like image 305
ozmo Avatar asked Aug 09 '10 02:08

ozmo


2 Answers

My thoughts (and I've been wrong before, just ask my wife) are that it's simply a holdover from earlier incarnations of the language.

Early versions of C did not allow you to declare variables anywhere you wanted in a function, they had to be at the top (or maybe at the start of a block, it's hard to remember off the top of my head since I rarely do that nowadays).

In addition, you have the understandable desire to set a variable only when you know what it should be. There's no point in initialising a variable to something if the next thing you're going to do with it is simply overwrite that value (that's where the performance people are coming from here).

That's why it's necessary to allow uninitialised variables though you still shouldn't use them before you initialise them, and the good compilers have warnings to let you know about it.

In C++ (and later incarnations of C) where you can create your variable anywhere in a function, you really should create it and initialise it at the same time. But that wasn't possible early on. You had to use something like:

int fn(void) {
    int x, y;
    /* Do some stuff to set y */
    x = y + 2;
    /* Do some more stuff */
}

Nowadays, I'd opt for:

int fn(void) {
    int y;
    /* Do some stuff to set y */
    int x = y + 2;
    /* Do some more stuff */
}
like image 92
paxdiablo Avatar answered Oct 03 '22 06:10

paxdiablo


The oldest excuse in programming : it improves performance!

edit: read your comments and I agree - years ago the focus on performance was on the number of CPU cycles. My first C compiler was traditional C (the one prior to ANSI C) and it allowed all sorts of abominations to compile. In these modern times performance is about the number of customer complaints. As I tell new graduates we hire - 'I don't care how quickly the program gives a wrong answer'. Use all the tools of modern compilers and development, write less bugs and everyone can go home on time.

like image 28
jqa Avatar answered Oct 03 '22 05:10

jqa