473,396 Members | 1,767 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Variable declaration and while loops

Hello,

This seems like an extremely basic question, and I'm a bit embarassed
that I can't answer it myself.

I just recently started using GCC and tried to type the following
code:

while ((int i = getint()) != 0)
{
/* something */
}

which my compiler has been supporting for a good few years. Under GCC
this doesn't compile. At first it didn't even occur to me that maybe
the code was invalid. I just thought GCC was being stupid. But then
it occurred to me that this probably really isn't valid C++, and that
my compiler has just been breaking the rule. Can anyone shed some
light? Can you declare a variable in a while loop similar to how you
can with a for loop?

Jun 18 '07 #1
10 4112
Zachary Turner wrote:
Hello,

This seems like an extremely basic question, and I'm a bit embarassed
that I can't answer it myself.

I just recently started using GCC and tried to type the following
code:

while ((int i = getint()) != 0)
Drop the "!= 0" part and you'll have a standard construct.
{
/* something */
}

which my compiler has been supporting for a good few years. Under GCC
this doesn't compile. At first it didn't even occur to me that maybe
the code was invalid. I just thought GCC was being stupid. But then
it occurred to me that this probably really isn't valid C++, and that
my compiler has just been breaking the rule. Can anyone shed some
light? Can you declare a variable in a while loop similar to how you
can with a for loop?
No, you cannot. Those are two different statements and they have
different syntax. You can, however, declare/define/initialise an object
in a 'while' or 'if' parentheses, but you cannot do it in an expression.

if (int i = getint())

is valid

if ((int i = getint()) != 0)

is not, although the semantics are the same. (you can replace 'if'
with 'while' above).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 18 '07 #2
Hi

Zachary Turner schreef:
I just recently started using GCC and tried to type the following
code:

while ((int i = getint()) != 0)
{
/* something */
}

which my compiler has been supporting for a good few years. Under GCC
this doesn't compile. At first it didn't even occur to me that maybe
the code was invalid. I just thought GCC was being stupid. But then
it occurred to me that this probably really isn't valid C++, and that
my compiler has just been breaking the rule. Can anyone shed some
light? Can you declare a variable in a while loop similar to how you
can with a for loop?
Yes, but you may not parenthesize it (a declaration is not an
expression). So, correctly, your code would read:

while(int i = getint())
{
/* something */
}

The condition in an if-, while-, switch- and even in a for-statement may
be a declaration with initialization. In this case, the condition
evaluates to the value of the declared variable, converted to bool.

Markus
Jun 18 '07 #3
"Victor Bazarov" <v.********@comAcast.netwrote in news:f562h2$sdg$1
@news.datemas.de:
Zachary Turner wrote:
>Hello,

This seems like an extremely basic question, and I'm a bit embarassed
that I can't answer it myself.

I just recently started using GCC and tried to type the following
code:

while ((int i = getint()) != 0)

Drop the "!= 0" part and you'll have a standard construct.
Personal style: ick. I prefer to explicitly test against 0 when dealing
with ints (I also prefer to explicitly mention NULL when dealing with
pointers too.) If the expression type is bool (or 99.9% of the time
intended to be treated as a bool, such as the void* return of streams.
It's not really intended to be used as a pointer, but it prevents other
unintentional implicit type conversion.), then I'll do the implicit test.

Jun 18 '07 #4
Andre Kostur wrote:
"Victor Bazarov" <v.********@comAcast.netwrote in news:f562h2$sdg$1
@news.datemas.de:
>Zachary Turner wrote:
>>Hello,

This seems like an extremely basic question, and I'm a bit
embarassed that I can't answer it myself.

I just recently started using GCC and tried to type the following
code:

while ((int i = getint()) != 0)

Drop the "!= 0" part and you'll have a standard construct.

Personal style: ick. I prefer to explicitly test against 0 when
dealing with ints (I also prefer to explicitly mention NULL when
dealing with pointers too.) If the expression type is bool (or 99.9%
of the time intended to be treated as a bool, such as the void*
return of streams. It's not really intended to be used as a pointer,
but it prevents other unintentional implicit type conversion.), then
I'll do the implicit test.
Yes, as a matter of style I like seeing ints tested explicitly against
zero, but for pointers I like saying 'if (pointer) '. The syntax is
also very convenient for streams (both C and C++), where you don't care
for the variable to survive beyond the point of check.

Compare

if (FILE* blah = fopen("somename", "rb")) {
// do something with 'blah'
}

and

{
FILE* blah = fopen("somename", "rb");
if (blah != NULL) {
// do something with 'blah'
}
}

Did you notice the extra pair of braces? Ick! Besides, the former
code reads better, IMNSHO. "If file opens, do something", compared
to "open blah. if blah is not NULL ..." [..Wait a minute? Why am I
checking for NULL when the term should be "opens"? so now I need to
introduce an extra utility function or macro:

inline bool opened_OK(FILE* f) { return f != NULL; }

and write

{
FILE* blah = fopen("somename", "rb");
if (opened_OK(blah)) {
// do something with 'blah'
}
}

Ick!]

See my point?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 18 '07 #5
"Victor Bazarov" <v.********@comAcast.netwrote in news:f56981$8c8$1
@news.datemas.de:
Andre Kostur wrote:
>"Victor Bazarov" <v.********@comAcast.netwrote in news:f562h2$sdg$1
@news.datemas.de:
>>Zachary Turner wrote:
Hello,

This seems like an extremely basic question, and I'm a bit
embarassed that I can't answer it myself.

I just recently started using GCC and tried to type the following
code:

while ((int i = getint()) != 0)

Drop the "!= 0" part and you'll have a standard construct.

Personal style: ick. I prefer to explicitly test against 0 when
dealing with ints (I also prefer to explicitly mention NULL when
dealing with pointers too.) If the expression type is bool (or 99.9%
of the time intended to be treated as a bool, such as the void*
return of streams. It's not really intended to be used as a pointer,
but it prevents other unintentional implicit type conversion.), then
I'll do the implicit test.

Yes, as a matter of style I like seeing ints tested explicitly against
zero, but for pointers I like saying 'if (pointer) '. The syntax is
also very convenient for streams (both C and C++), where you don't care
for the variable to survive beyond the point of check.

Compare

if (FILE* blah = fopen("somename", "rb")) {
// do something with 'blah'
}

and

{
FILE* blah = fopen("somename", "rb");
if (blah != NULL) {
// do something with 'blah'
}
}

Did you notice the extra pair of braces? Ick! Besides, the former
code reads better, IMNSHO. "If file opens, do something", compared
to "open blah. if blah is not NULL ..." [..Wait a minute? Why am I
checking for NULL when the term should be "opens"? so now I need to
introduce an extra utility function or macro:
Yep... but hopefully your function is small enough that the FILE* has the
scope of the entire function anyway. (Or suffer with a FILE* that has a
larger scope than strictly necessary).
inline bool opened_OK(FILE* f) { return f != NULL; }

and write

{
FILE* blah = fopen("somename", "rb");
if (opened_OK(blah)) {
// do something with 'blah'
}
}
This would be the pain of using C-style functions :) Use streams :)
>
Ick!]

See my point?
Sure... the style doesn't work for you. Arguably if you need to add
additional braces, perhaps you should consider refactoring that piece of
code into its own function.

Jun 18 '07 #6
Andre Kostur wrote:
"Victor Bazarov" <v.********@comAcast.netwrote in news:f56981$8c8$1
@news.datemas.de:
>Andre Kostur wrote:
>>"Victor Bazarov" <v.********@comAcast.netwrote in
news:f562h2$sdg$1 @news.datemas.de:

Zachary Turner wrote:
Hello,
>
This seems like an extremely basic question, and I'm a bit
embarassed that I can't answer it myself.
>
I just recently started using GCC and tried to type the following
code:
>
while ((int i = getint()) != 0)

Drop the "!= 0" part and you'll have a standard construct.

Personal style: ick. I prefer to explicitly test against 0 when
dealing with ints (I also prefer to explicitly mention NULL when
dealing with pointers too.) If the expression type is bool (or
99.9% of the time intended to be treated as a bool, such as the
void* return of streams. It's not really intended to be used as a
pointer, but it prevents other unintentional implicit type
conversion.), then I'll do the implicit test.

Yes, as a matter of style I like seeing ints tested explicitly
against zero, but for pointers I like saying 'if (pointer) '. The
syntax is also very convenient for streams (both C and C++), where
you don't care for the variable to survive beyond the point of check.

Compare

if (FILE* blah = fopen("somename", "rb")) {
// do something with 'blah'
}

and

{
FILE* blah = fopen("somename", "rb");
if (blah != NULL) {
// do something with 'blah'
}
}

Did you notice the extra pair of braces? Ick! Besides, the former
code reads better, IMNSHO. "If file opens, do something", compared
to "open blah. if blah is not NULL ..." [..Wait a minute? Why am I
checking for NULL when the term should be "opens"? so now I need to
introduce an extra utility function or macro:

Yep... but hopefully your function is small enough that the FILE* has
the scope of the entire function anyway. (Or suffer with a FILE*
that has a larger scope than strictly necessary).
Why suffer?
>
> inline bool opened_OK(FILE* f) { return f != NULL; }

and write

{
FILE* blah = fopen("somename", "rb");
if (opened_OK(blah)) {
// do something with 'blah'
}
}

This would be the pain of using C-style functions :) Use streams :)
Goes the same way

if (std::ifstream blah("somename", ios::binary)) {
// do something with blah
}

Works like a charm with any C++ objects that define operator void* or
operator bool to indicate "good state".
>
>>
Ick!]

See my point?

Sure... the style doesn't work for you. Arguably if you need to add
additional braces, perhaps you should consider refactoring that piece
of code into its own function.
Nope. I have a perfectly working language construct that I use instead.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 18 '07 #7
Thanks for the response. It appears (to no real surprise to myself)
that I'm just getting crazy in my old age. I went back and tried my
compiler which I thought accepted this and it complains as well. I
know I've declared variables in while loop parentheses hundreds if not
thousands of times, I guess I never had it parenthesized like I
thought I did. Not sure what gave me the idea to try it all of a
sudden!

Zach

On Jun 18, 8:49 am, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Zachary Turner wrote:
Hello,
This seems like an extremely basic question, and I'm a bit embarassed
that I can't answer it myself.
I just recently started using GCC and tried to type the following
code:
while ((int i = getint()) != 0)

Drop the "!= 0" part and you'll have a standard construct.
{
/* something */
}
which my compiler has been supporting for a good few years. Under GCC
this doesn't compile. At first it didn't even occur to me that maybe
the code was invalid. I just thought GCC was being stupid. But then
it occurred to me that this probably really isn't valid C++, and that
my compiler has just been breaking the rule. Can anyone shed some
light? Can you declare a variable in a while loop similar to how you
can with a for loop?

No, you cannot. Those are two different statements and they have
different syntax. You can, however, declare/define/initialise an object
in a 'while' or 'if' parentheses, but you cannot do it in an expression.

if (int i = getint())

is valid

if ((int i = getint()) != 0)

is not, although the semantics are the same. (you can replace 'if'
with 'while' above).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

Jun 18 '07 #8
On Jun 18, 7:40 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Andre Kostur wrote:
"Victor Bazarov" <v.Abaza...@comAcast.netwrote in news:f56981$8c8$1
@news.datemas.de:
Compare
if (FILE* blah = fopen("somename", "rb")) {
// do something with 'blah'
}
and
{
FILE* blah = fopen("somename", "rb");
if (blah != NULL) {
// do something with 'blah'
}
}
Yes. The second is readable, the first isn't.
Did you notice the extra pair of braces? Ick! Besides, the former
code reads better, IMNSHO. "If file opens, do something", compared
to "open blah. if blah is not NULL ..." [..Wait a minute? Why am I
checking for NULL when the term should be "opens"? so now I need to
introduce an extra utility function or macro:
Yep... but hopefully your function is small enough that the FILE* has
the scope of the entire function anyway. (Or suffer with a FILE*
that has a larger scope than strictly necessary).
Why suffer?
Why, quite? If the function is long enough for it to make a
difference, it's too long.
This would be the pain of using C-style functions :) Use streams :)
Goes the same way

if (std::ifstream blah("somename", ios::binary)) {
// do something with blah
}
Which is just as bad?

This is a major misfeature of C++; all it leads to is unreadable
code.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 18 '07 #9
James Kanze wrote:
[.. style differences identified ..]
This is a major misfeature of C++; all it leads to is unreadable
code.
Readability of the code is NOT an objective characteristic, we
should abandon this religious debate right here. Deal?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 18 '07 #10
"Victor Bazarov" <v.********@comAcast.netwrote in news:f56oqb$42v$1
@news.datemas.de:
James Kanze wrote:
>[.. style differences identified ..]
This is a major misfeature of C++; all it leads to is unreadable
code.

Readability of the code is NOT an objective characteristic, we
should abandon this religious debate right here. Deal?
Kinda why I stopped... this is all up to personal preference. I like my
way, you like yours, we're not hurting each other....
Jun 18 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

83
by: Alexander Zatvornitskiy | last post by:
Hello All! I'am novice in python, and I find one very bad thing (from my point of view) in language. There is no keyword or syntax to declare variable, like 'var' in Pascal, or special syntax in...
23
by: stewart.midwinter | last post by:
No doubt I've overlooked something obvious, but here goes: Let's say I assign a value to a var, e.g.: myPlace = 'right here' myTime = 'right now' Now let's say I want to print out the two...
3
by: Thomas Matthews | last post by:
Hi, While coding programs, I cam about a conundrum regarding variables defined in an iterative loop. The issue is whether it is more efficient to factor the definition out of the loop or...
32
by: Wenjie | last post by:
Hello, We had a code review with the argument of whether "i" is out of scope as illustrated below: for (int i=0; i<2004; i++) { doSomething(i); }
134
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that...
27
by: Mike P | last post by:
I will be passing my function a two dimensional array of varying length. Within that array is one data point, and the number of times it should loop through. So, for example, I might pass this...
4
by: Ray | last post by:
Hello, I think I've had JavaScript variable scope figured out, can you please see if I've got it correctly? * Variables can be local or global * When a variable is declared outside any...
12
by: PSN | last post by:
The following code compiles fine with GCC. Isnt this supposed to be a redefinition of 'i' error ... main() { for (int i=0; i<10; i++) cout << i << endl; for (int i=10; i>0; i--) cout << i...
4
by: falderals | last post by:
Error 1 Variable 'j' hides a variable in an enclosing block. How do I fix this error? Thanks Protected Sub ComputeA(ByVal i As Integer) Dim sk As Single Dim l As Integer = nn.N_Layers-1 '...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.