|
From: Ioannis V. <no...@ho...> - 2002-08-08 20:35:20
|
> -----Original Message-----
> From: dev...@li...=20
> [mailto:dev...@li...] On Behalf=20
> Of Carlos Garc=EDa del Monte
> Sent: Thursday, August 08, 2002 9:31 PM
> To: dev-cpp-users-list
> Subject: Re: [Dev-C++] compiler psychiatrics
>=20
>=20
> > Great! As you see it was not a compiler's issue.
>=20
> Great! Yes!
> Now I've found and reviewed one piece of code which has the=20
> for(int i) I
> said it didn't work. It is an author error (author of some=20
> code example I
> used). The ANSI about declaring for is something like "you can declare
> inside a for statement in the way (int i =3D 0[...]), but you=20
> can't use it
> later outside it, if you want you have to declare it just=20
> before the for:
> int i; for(i=3D0[...]) or redeclare it".
>=20
> I read first C/C++, an old edition and centered in C, so it=20
> said nothing
> about possibility of declaring in the for.
> Later I bought the "C++ how to program" (which couple of=20
> inexactitudes I
> found, some misleading things about bitfields, I suspect are=20
> due to the
> translator (I bought it in spanish) who knows bad spanish=20
> (!!!)), but I knew
> for, and I only noticed "can be declared in", but not read=20
> "out of it it is
> out of scope". And later I got some code examples from some=20
> sites (I don't
> remember where) where they were used later, and that misled=20
> me, thinking
> that the error wasn't only outside, but inside, too.
>=20
> It's a bad thing that the last for/while rare thing is=20
> deleted. I would see
> a possibly frequent error. (or you a compiler strange=20
> behavior, hehehehe)
> and I would learn to see a error now I am unable to see (Feel I need a
> phrase about the sea being free).
> Greets.
Lets clarify things a bit here. A variable has scope inside the block it
was defined. For example:
void f()
{
int i=3D0;
i++;
// local scope
{
int j=3D0;
j+=3D2;
} // end of j's scope. j is destroyed.
// another local scope
{
// This is a different i
int i=3D7;
=20
i*=3D2;
// The local i has become 14, the first i remains 1
} // end of local i's scope. i dies.
// Here we see the i with value 1
}// end of function and i's scope. i is destroyed
This applies both in C & C++. The difference between C & C++ is that in
C90 you have to define the variables in the beginning of a scope, while
in C++98 you can define it in the first place you will need it in a
scope. I 'll not discuss about C99 so as to not confuse things.
Now in C90 when we wanted to define a local variable for a for-loop we
did this trick:
void f(void)
{
{
int i;
for(i=3D0; i<10; i++)
/* stuff */
}
/* i dies */
=20
/* ... */
}
=20
Now in C++98=20
we can do
void f()
{
for(int i=3D0; i<10; i++)
{
// stuff
=20
} // i dies here
}
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.cjb.net
* Alternative URL: http://run.to/noicys
=20
|