Re: Bug in g++'s int constructor?
Re: Bug in g++'s int constructor?
- Subject: Re: Bug in g++'s int constructor?
- From: "Clark S. Cox III" <email@hidden>
- Date: Fri, 29 Mar 2002 04:05:40 -0500
On 03/28/2002 17:42, "Mark" <email@hidden> wrote:
>
Hi everyone,
>
>
Please excuse me if this is off topic for this list, I really didn't
>
know where else to post it, aside for maybe darwin-dev or whatnot.
>
I believe I have inadvertently discovered a bug in g++. ( 2.95 I
>
believe, stock OS 10.1.3 with most recent dev tools installed )
>
The int constructor is only initializing an int to 0 in a member
>
function on the first run of that function. All calls to that function,
>
after the initial, get the SAME value that the int had when running the
>
member function the first time through.
>
>
i.e. this is what happened to me...
>
On the first run insert works perfectly, next time its called sum was
>
reallocated in the same spot with the same value every time. So the
>
program would hang, insert would never return true (ITEM was inserted)
>
because the sum of everything in the array + ITEM would ALWAYS be
>
greater then CAPACITY.
>
>
bool bag::insert( const int ITEM )
>
{
>
int sum;
>
>
for( x = 0; x <= ARRAY_INDEX; x++ )
>
{
>
sum += data[x];
>
}
>
>
if( (sum + ITEM) <= CAPACITY )
>
{
>
data[ ARRAY_INDEX ] = ITEM;
>
ARRAY_INDEX++;
>
return ( true );
>
}
>
else
>
return ( false );
>
}
>
>
Granted just changing int sum; to int sum = 0; fixes the problem, but
>
doesn't change the fact that this is a bug.
>
To the point, has anyone else discovered this? Filled a bug report?
>
Should I?
That is not a bug, you were just lucky (or unlucky) that it worked the
first time. (Also, I would be weary of any CS teacher that was making an
assumption like this). According to the C++ standard, automatic variables
with a built-in or pointer type (or with no constructor) have an unspecified
value unless explicitly initialized. This means that you cannot count on the
value of any of the variables in the following program:
struct foo {
int i;
float f;
};
Int main()
{
int i;
float f;
char c;
double d;
float f;
foo foo;
//And so on
}
Built in types only have a constructor when it is explicitly called:
int i = int(); //Same as int i=0;
float f = float(); //Same as float f=0;
//etc.
--
Clark S. Cox III
http://clarkcox.dyndns.org/
email@hidden
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.