char[] initialization

Walter Bright newshound at digitalmars.com
Sat Jul 29 15:00:47 PDT 2006


Carlos Santander wrote:
> Hasan Aljudy escribió:
>>
>>
>> Still missing my point.
>> in C/C++ that's a problem because un-initialized variables carry garbage.
>> in D, it's not; if you init them to a reasonable valid default, this 
>> problem won't exist anymore.
>>
>> If un-initializing is bad just for its own sake .. then the compiler 
>> should detect it and issue an error/warning, otherwise it should 
>> default to a reasonable valid value; in this case, zero for chars and 
>> floats.
> 
> The issue here is, a "reasonable valid default" will change from one app 
> to the other, one function to the next, one variable to another, so the 
> intention here is force the developer to be explicit about his/her 
> intentions.
> 
> Walter has said in the past that if there was a NAN for int/long/etc, 
> he'd use that instead of 0.
> 

That's right. Also, given:

	int x;

	foo(x);

it is impossible for the maintenance programmer to distinguish between:

1) x is meant to be 0
2) the original programmer forgot to initialize x to 3, and there's a 
bug in the program

Ok, fine, so why doesn't the compiler just squawk about referencing 
uninitialized variables? Consider:

	int x;
	...
	if (...)
	{	x = 3;
		...
	}
	...
	if (...)
	{	...
		foo(x);
	}

There is no way for the compiler to determine that x in foo(x) is always 
initialized. So it must assume otherwise, and squawk about it. So how 
does our harried programmer fix it?

	int x = some-random-value;
	...
	if (...)
	{	x = 3;
		...
	}
	...
	if (...)
	{	...
		foo(x);
	}

The compiler is now happy, but pity the poor maintenance programmer. He 
notices the some-random-value, and wonders what that value means. He 
analyzes the code, and discovers that that value is never used. Was it 
intended to be used? Did some previous maintenance programmer break the 
code? What's going on here?

My take on programming languages is that the semantics should have the 
obvious meaning - i.e. if the programmer initializes a variable to a 
value, that value should have meaning. He should not have to initialize 
a variable because of some subtle *side effect* such initialization has.

Programmers should not be required to add dead assignments, unreachable 
code, etc., just to keep the compiler happy.



More information about the Digitalmars-d mailing list