473,326 Members | 2,438 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,326 software developers and data experts.

for vs. while

Hi

I read somewhere that is better to use while instead of for loop in
this case below:

vector<mytypevmt;

instead of
for ( int j=0; j < static_cast<int(vmt.size()); j++)
vmt[j].method(args);

int j = 0;
while ( j < static_cast<int(vmt.size()) )
vmt[j++].method(args)
is this ok, also not the [j++] which uses "j" before increments it to
the next one.

thanks

Oct 27 '06 #1
16 1661
Gary Wessle wrote:
I read somewhere that is better to use while instead of for loop in
this case below:

vector<mytypevmt;

instead of
for ( int j=0; j < static_cast<int(vmt.size()); j++)
vmt[j].method(args);

int j = 0;
while ( j < static_cast<int(vmt.size()) )
vmt[j++].method(args)
is this ok, also not the [j++] which uses "j" before increments it to
the next one.
I usually write

for (vector<mytype>::size_type j = 0, s = vmt.size(); j < s; ++j)
vmt[j].method(args);

or

for (vector<mytype>::iterator it = vmt.begin(), e = vmt.end();
it != e; ++it)
(*it).method(args);

or

vector<mytype>::iterator it = vmt.begin(), e = vmt.end();
while (it != e)
(*it++).method(args);

, depending on how I feel at the time. Using 'int' and doing the
'static_cast' is definitely not normal.

Now, as to what you "read somewhere", I am not sure, how do you
define "better"?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 27 '06 #2
Gary Wessle <ph****@yahoo.comwrote:
I read somewhere that is better to use while instead of for loop in
this case below:

vector<mytypevmt;

instead of
for ( int j=0; j < static_cast<int(vmt.size()); j++)
vmt[j].method(args);

int j = 0;
while ( j < static_cast<int(vmt.size()) )
vmt[j++].method(args)
is this ok, also not the [j++] which uses "j" before increments it to
the next one.
Well, personally I think using random access in this situation is a
little off. Better would be to use an iterator and increment through it.

But to answer your given question. I'd like to see that "somewhere" that
you read it because it seems quite silly to me.

1) In the former case, the scope of 'j' is contained in the for loop
block, while in the latter case it extends throughout the rest of the
function.

2) In the former case, the looping variable is contained within one line
of code, while in the latter case, initialization, loop end, and
increment are on separate lines.

Why would one prefer the while loop over a for loop in this particular
situation?

--
To send me email, put "sheltie" in the subject.
Oct 27 '06 #3
On 27 Oct 2006 10:49:24 +1000 in comp.lang.c++, Gary Wessle
<ph****@yahoo.comwrote,
>I read somewhere that is better to use while instead of for loop in
this case below:
Use the one that to you is the clearest and most direct expression
of what you are trying to say. It's exactly the same to the
compiler.

I like to use 'for' when a simple variable increments from one value
to another, like an old FORTRAN DO loop, as in your example; and
'while' when the pattern is more complex.

Oct 27 '06 #4
Gary Wessle posted:
Hi

I read somewhere that is better to use while instead of for loop in
this case below:

vector<mytypevmt;

instead of
for ( int j=0; j < static_cast<int(vmt.size()); j++)
vmt[j].method(args);

int j = 0;
while ( j < static_cast<int(vmt.size()) )
vmt[j++].method(args)
is this ok, also not the [j++] which uses "j" before increments it to
the next one.
Three things to point out:

(1) Your use of "int" is probably bogus.
(2) vmt.size() is evaluated for each iteration of the loop; is this what
you want?
(3) Your usage of the postfix operator in the "for" example is frowned
upon.

If I were to assume that vmt.size() need only be evaluated once, then maybe
I'd write:

extern vector<Avec; /* Defined somewhere else... */

vector<A>::size_type const len = vec.size();

vector<A>::size_type i = 0;

while (i < len) vec[i++].Method(args);

--

Frederick Gotham
Oct 27 '06 #5

Frederick Gotham wrote:
Gary Wessle posted:
Hi

I read somewhere that is better to use while instead of for loop in
this case below:

vector<mytypevmt;

instead of
for ( int j=0; j < static_cast<int(vmt.size()); j++)
vmt[j].method(args);

int j = 0;
while ( j < static_cast<int(vmt.size()) )
vmt[j++].method(args)
is this ok, also not the [j++] which uses "j" before increments it to
the next one.

Three things to point out:

(1) Your use of "int" is probably bogus.
std::size_t ???
(2) vmt.size() is evaluated for each iteration of the loop; is this what
you want?
Could it perhaps be cached, in which case it would not matter? Also,
could this be considered premature optimization? size() in the case of
the vector would probably be implemented as an inline call. I think
eventually it would be cached.
(3) Your usage of the postfix operator in the "for" example is frowned
upon.
I have heard from good sources (reading discussion on
comp.lang.moderated.c++) that it does not really matter for builtin
types (If you consider that whether returning a reference or a copy of
a builtin type..., what does it matter). All said, looking at the
implementation of modern libraries, all of the ones I've seen uses
pre-increment. I use it because its consistent with how I would do it
when using non-builtins.

The reason for this (OP), is that during overloading a post-increment
(for non-builtin types) does the following (Makes a copy of the current
value, pre-increments it and then returns the copy). Post-increment is
therefore often implemented in terms of Pre-increment, and is always
less efficient for non-builtins:

//Assuming value_ an integer member of Int.
//--- post-increment
Int Int::operator++( int )
{
Int i( value_ );
++(*this);
return i;
}
//--- pre-increment
Int& Int::operator++()
{
++value_;
return *this;
}

Regards,

Werner

Oct 27 '06 #6
werasm:
>Three things to point out:

(1) Your use of "int" is probably bogus.

std::size_t ???

size_t might be prefereable, yes, but then I'm not familiar with
std::vector.

>(2) vmt.size() is evaluated for each iteration of the loop; is this what
you want?

Could it perhaps be cached, in which case it would not matter? Also,
could this be considered premature optimization? size() in the case of
the vector would probably be implemented as an inline call. I think
eventually it would be cached.

I can go to the petrol station and hope that they put premium high-
performance petrol in my car. I could just hope, or I could explicitly tell
them to. _Your_ code hopes. _My_ code makes it happen.

>(3) Your usage of the postfix operator in the "for" example is frowned
upon.

I have heard from good sources (reading discussion on
comp.lang.moderated.c++) that it does not really matter for builtin
types (If you consider that whether returning a reference or a copy of
a builtin type..., what does it matter).

Indeed, if the resultant value is discarded, then both postincrement and
preincrement can be implemented identicall. Even if the resultant value
_isn't_ discarded, there's still no need for a temporary when dealing with
intriniscs. The following:

i = j++;

can be turned into:

i = j, ++j;

All said, looking at the implementation of modern libraries, all of the
ones I've seen uses pre-increment. I use it because its consistent with
how I would do it when using non-builtins.

I use it because:

(1) It's consistent with how all the other assignment operators work.
(2) It's more efficient when dealing with user-defined types.

--

Frederick Gotham
Oct 27 '06 #7
Frederick Gotham wrote:
werasm:

>>>Three things to point out:

(1) Your use of "int" is probably bogus.

std::size_t ???

size_t might be prefereable, yes, but then I'm not familiar with
std::vector.
>>>(2) vmt.size() is evaluated for each iteration of the loop; is this what
you want?

Could it perhaps be cached, in which case it would not matter? Also,
could this be considered premature optimization? size() in the case of
the vector would probably be implemented as an inline call. I think
eventually it would be cached.

I can go to the petrol station and hope that they put premium high-
performance petrol in my car. I could just hope, or I could explicitly tell
them to. _Your_ code hopes. _My_ code makes it happen.
What utter rubbish.

Write code that you (and others who follow) can understand. If
performance is an issue, profile and optimise.

--
Ian Collins.
Oct 27 '06 #8
Ian Collins:

>I can go to the petrol station and hope that they put premium high-
performance petrol in my car. I could just hope, or I could explicitly
tell them to. _Your_ code hopes. _My_ code makes it happen.
What utter rubbish.

Write code that you (and others who follow) can understand. If
performance is an issue, profile and optimise.

Which is why my code is more efficient than yours.

--

Frederick Gotham
Oct 27 '06 #9
Frederick Gotham wrote:
werasm:
>>Three things to point out:

(1) Your use of "int" is probably bogus.
std::size_t ???


size_t might be prefereable, yes, but then I'm not familiar with
std::vector.
Like most containers, vector defines its own size type,
vector<foo>::size_type
Oct 27 '06 #10
Frederick Gotham wrote:
Ian Collins:

>>I can go to the petrol station and hope that they put premium high-
performance petrol in my car. I could just hope, or I could explicitly
tell them to. _Your_ code hopes. _My_ code makes it happen.
What utter rubbish.

Write code that you (and others who follow) can understand. If
performance is an issue, profile and optimise.


Which is why my code is more efficient than yours.
A fairly absurd assertion. Unless you're writing exceptionally simple
bits of code, decisions about algorithm and data structure design far
outweigh these minute details.
Oct 27 '06 #11
Frederick Gotham wrote:
Ian Collins:
>>>I can go to the petrol station and hope that they put premium high-
performance petrol in my car. I could just hope, or I could explicitly
tell them to. _Your_ code hopes. _My_ code makes it happen.

What utter rubbish.

Write code that you (and others who follow) can understand. If
performance is an issue, profile and optimise.

Which is why my code is more efficient than yours.
Again, rubbish.

One of the beauties of C++ is the compiler's ability to inline function
calls. This enables us to wrap messy logic in a wrapper function and
not worry about the overhead. The speculative addition of a local
variable adds nothing to the readability of the code.

Never speculate on the efficiency of an operation, if you think you have
a performance issue, profile.

Compare the performance of the two paths though this code:

#include <vector>
#include <iostream>

int main( int argc, char** argv ){
std::vector<unsignedvec;

for( unsigned n = 0; n < 10000; ++n ){
vec.push_back(n);
}

unsigned total = 0;

if( argc == 1 ){
for( int loop = 0; loop < 10000; ++loop ){
unsigned sum = 0;

for( size_t n = 0; n < vec.size(); ++n ){
sum += vec[n];
}
total += sum;
}
}
else{
const size_t size = vec.size();

for( int loop = 0; loop < 10000; ++loop ){
unsigned sum = 0;

for( size_t n = 0; n < size; ++n ){
sum += vec[n];
}

total += sum;
}
}

std::cout << "total: " << total << std::endl;
}
--
Ian Collins.
Oct 27 '06 #12
Ian Collins:
One of the beauties of C++ is the compiler's ability to inline function
calls.

Or rather the "permission" which the Standard gives to implementations to
inline function calls.

Contrast "permit" with "necessitate".

This enables us to wrap messy logic in a wrapper function and
not worry about the overhead.

Not it doesn't, not according to the Standard in anyway.

The speculative addition of a local variable adds nothing to the
readability of the code.

There was nothing "speculative" about my addition of the local variable --
I actually added it.

The functionality of code is the primary concern.

Never speculate on the efficiency of an operation, if you think you have
a performance issue, profile.

I only write portable algorithms. Therefore, I don't make presumptions as
to which compilers might inline what and so forth. I write code which
should work efficiently, without depending on implementation-specific
optimisations. Therefore, if the conditional compartment of a "for" loop
invokes a function, I'll think to myself, "Hmm... do I want to invoke this
function upon every iteration, or just once at the start?".

--

Frederick Gotham
Oct 27 '06 #13
Frederick Gotham wrote:
Ian Collins:
>>One of the beauties of C++ is the compiler's ability to inline function
calls.

Or rather the "permission" which the Standard gives to implementations to
inline function calls.

Contrast "permit" with "necessitate".
A C++ compiler that doesn't inline trivial methods isn't worthy of the
name. Have a read of the Design and Evolution of C++ some time.
>
>>This enables us to wrap messy logic in a wrapper function and
not worry about the overhead.

Not it doesn't, not according to the Standard in anyway.
In the real world, it does.
>
>>The speculative addition of a local variable adds nothing to the
readability of the code.

There was nothing "speculative" about my addition of the local variable --
I actually added it.
It's clear you added it, the speculation was that it would improve
performance. It may also impede the optimiser.
>>Never speculate on the efficiency of an operation, if you think you have
a performance issue, profile.

I only write portable algorithms. Therefore, I don't make presumptions as
to which compilers might inline what and so forth. I write code which
should work efficiently, without depending on implementation-specific
optimisations. Therefore, if the conditional compartment of a "for" loop
invokes a function, I'll think to myself, "Hmm... do I want to invoke this
function upon every iteration, or just once at the start?".
Well that's up to you.

Just out of interest, the example I posted returns identical run time
when compiled with gcc and is significantly faster using size() when
compiled with Sun CC. So in one case, there is nothing gained and in
the other, there is a significant loss.

--
Ian Collins.
Oct 27 '06 #14
Frederick Gotham wrote:
Ian Collins:
>One of the beauties of C++ is the compiler's ability to inline
function calls.


Or rather the "permission" which the Standard gives to
implementations to inline function calls.

Contrast "permit" with "necessitate".
Buy a new compiler, if the one you use doesn't work properly.

Trying to optimize for broken compilers isn't the best way to write
portable code.
Bo Persson
Oct 28 '06 #15
In article <11*********************@h48g2000cwc.googlegroups. com>,
werasm <w_*****@telkomsa.netwrote:
>Frederick Gotham wrote:
>(3) Your usage of the postfix operator in the "for" example is frowned
upon.

I have heard from good sources (reading discussion on
comp.lang.moderated.c++) that it does not really matter for builtin
types (If you consider that whether returning a reference or a copy of
a builtin type..., what does it matter). All said, looking at the
implementation of modern libraries, all of the ones I've seen uses
pre-increment. I use it because its consistent with how I would do it
when using non-builtins.
The counter counter argument though is if you were to change
the type of the builtin to a non-builtin, then you probably
need to go in a change each and every loop. There's probably
some other reasons too I'm not thinking of.
--
Greg Comeau / 20 years of Comeauity! Intel Mac Port now in beta!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Oct 30 '06 #16

Greg Comeau wrote:
The counter counter argument though is if you were to change
the type of the builtin to a non-builtin, then you probably
need to go in a change each and every loop. There's probably
some other reasons too I'm not thinking of.
Good point. I cannot remember when last I really used post-increment,
though. I assumed that the OP was asking the question in terms of
speed. I've heard rumours before that assembler generated from while
code was faster than assembler generated from for code. I believe that
they are old rumours though, as nowadays (I suppose) most compilers
optimize the loop to be the most efficient possibility anyway. I just
said (or implied) that in terms of speed, I did not think pre-and
post-increment for builtin types were that much different in terms of
efficiency. For reasons mentioned by me (and this good reason mentioned
by you), I would prefer pre-increment. Another thing (possibly rumour)
I've heard was that initial implementations of STL used post increment
- true?

Regards,

Werner

Oct 30 '06 #17

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

Similar topics

33
by: Diez B. Roggisch | last post by:
Hi, today I rummaged through the language spec to see whats in the for ... else: for me. I was sort of disappointed to learn that the else clauses simply gets executed after the loop-body -...
24
by: Andrew Koenig | last post by:
PEP 315 suggests that a statement such as do: x = foo() while x != 0: bar(x) be equivalent to while True:
4
by: James E Koehler | last post by:
I can't get the WHILE statement to work in MySQL. The version of MySQL that I am using is: Ver 12.16 Distrib 4.0.6-gamma, for Win95/Win98 (i32) running on Windows MX. Here is the relevant...
9
by: JS | last post by:
#include <stdio.h> main(){ int c, i, nwhite, nother; int ndigit; nwhite = nother = 0; for (i = 0; i < 10; ++i)
147
by: Michael B Allen | last post by:
Should there be any preference between the following logically equivalent statements? while (1) { vs. for ( ;; ) { I suspect the answer is "no" but I'd like to know what the consensus is
12
by: Howard | last post by:
Hello everyone (total VB.NET beginner here), I'm reading the "SAMS Teach Yourself VB.NET In 21 Days" book, and came across an exercise that I can't get to work. The exercise asks that you create...
4
by: Gary | last post by:
Hi, I get this error " " when my web page run, what does it mean? Hope someone can help!!! Gary
11
by: Rene | last post by:
Quick question, what is the point for forcing the semicolon at the end of the while statement? See example below: x = 0; do { x = x + 1; }while (x < 3); What's the point of having the...
5
by: Alex | last post by:
Hi I just want to clear something up in my head with while loops and exceptions. I'm sure this will probably be a no brainer for most. Check this simple pseudo-code out (vb.net): ...
16
by: koutoo | last post by:
I start my code with some constants then a while statement. But I have some For statements towards the end within the While statement where I start getting some errors. I'm hoping I won't have to...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.