PHWinfo banniere

Titres
PORTAIL ANNUAIRE ARTICLES COMPARATEUR HÉBERGEURS DEVIS FORUMS RÉDUCTEUR D'URL
Précédent   PHWinfo > Autres forums > Forum Programmation & Conception > comp.lang.cplus > i++ or ++i ?
S'inscrire FAQ Membres Recherche Messages du jour Marquer les forums comme lus
i++ or ++i ?

Réponse
 
LinkBack Outils de la discussion
Vieux 08/02/2008, 19h00   #1
John Brawley
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut i++ or ++i ?

Please pardon a maybe very stupid question?
I've read and reread Bjarne Stroustrup on this, and I still don't "get it,"
so I wrote this to me understand, and now I _really_ don't "get it."
Why, if one increments before, and the other after, do these snippets output
exactly the same?


#include <iostream>

int main() {
for(int i=0; i<10; i++)
std::cout<<i<<", ";
std::cout<<"\n";
for(int i=0;i<10;++i)
std::cout<<i<<", ";
std::cout<<"\n";
int b=7;
b++; std::cout<<b;
int c=7;
++c; std::cout<<"\n"<<c;
//????????? why? same outputs!
return 0;
}

_Same_output_.
What's the difference?
(I use these in a program, which doesn't crash....)


--
Peace
JB
jb@tetrahedraverse.com
Web: http://tetrahedraverse.com



  Réponse avec citation
Vieux 08/02/2008, 19h10   #2
fred.l.kleinschmidt@boeing.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

On Feb 8, 11:00am, "John Brawley" <jgbraw...@charter.net> wrote:
> Please pardon a maybe very stupid question?
> I've read and reread Bjarne Stroustrup on this, and I still don't "get it,"
> so I wrote this to me understand, and now I _really_ don't "get it."
> Why, if one increments before, and the other after, do these snippets output
> exactly the same?
>
> #include <iostream>
>
> int main() {
> for(int i=0; i<10; i++)
> std::cout<<i<<", ";
> std::cout<<"\n";
> for(int i=0;i<10;++i)
> std::cout<<i<<", ";
> std::cout<<"\n";
> int b=7;
> b++; std::cout<<b;
> int c=7;
> ++c; std::cout<<"\n"<<c;
> //????????? why? same outputs!
> return 0;
>
> }
>
> _Same_output_.
> What's the difference?
> (I use these in a program, which doesn't crash....)
>

Try this and see:

int b=7;
std::cout << b++ <<endl;
int c=7;
std::cout << ++c << endl;
--
Fred Kleinschmidt
  Réponse avec citation
Vieux 08/02/2008, 19h11   #3
Hans Mull
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

John Brawley schrieb:
> Please pardon a maybe very stupid question?
> I've read and reread Bjarne Stroustrup on this, and I still don't "get it,"
> so I wrote this to me understand, and now I _really_ don't "get it."
> Why, if one increments before, and the other after, do these snippets output
> exactly the same?
>
>
> #include <iostream>
>
> int main() {
> for(int i=0; i<10; i++)
> std::cout<<i<<", ";
> std::cout<<"\n";
> for(int i=0;i<10;++i)
> std::cout<<i<<", ";
> std::cout<<"\n";
> int b=7;
> b++; std::cout<<b;
> int c=7;
> ++c; std::cout<<"\n"<<c;
> //????????? why? same outputs!
> return 0;
> }
>
> _Same_output_.
> What's the difference?
> (I use these in a program, which doesn't crash....)
>
>

Maybe it will you do define the difference between ++i and i++;

The statements do the same with one difference:
The value of the statement "++i" is i+1
while the value of i++ is i:

#include <iostream>
using namespace std;

int main()
{
int i=6;
cout << "i++: " << i++ << endl; //Will return i = 6
int j=6;
cout << "++i: " << ++i << endl; //Will return i+1 = 7
return 0;
}

I hope this will you!

Kind regards, Hans
  Réponse avec citation
Vieux 08/02/2008, 19h39   #4
Daniel T.
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

"John Brawley" <jgbrawley@charter.net> wrote:

> Please pardon a maybe very stupid question?
> I've read and reread Bjarne Stroustrup on this, and I still don't "get it,"
> so I wrote this to me understand, and now I _really_ don't "get it."
> Why, if one increments before, and the other after, do these snippets output
> exactly the same?
>
> #include <iostream>
>
> int main() {
> for(int i=0; i<10; i++)
> std::cout<<i<<", ";
> std::cout<<"\n";
> for(int i=0;i<10;++i)
> std::cout<<i<<", ";
> std::cout<<"\n";
> int b=7;
> b++; std::cout<<b;
> int c=7;
> ++c; std::cout<<"\n"<<c;
> //????????? why? same outputs!
> return 0;
> }
>
> _Same_output_.
> What's the difference?
> (I use these in a program, which doesn't crash....)


And lastly, this may . When overloading the two operators, the
canonical implementations are:

class T {
public:
//prefix operator
T& operator++() {
// increment this
return *this;
}

//postfix operator
T operator++(int) {
T tmp( *this );
// increment this
return tmp;
}
};
  Réponse avec citation
Vieux 08/02/2008, 19h44   #5
Andrey Tarasevich
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

John Brawley wrote:
> ...
> #include <iostream>
>
> int main() {
> for(int i=0; i<10; i++)
> std::cout<<i<<", ";
> std::cout<<"\n";
> for(int i=0;i<10;++i)
> std::cout<<i<<", ";
> std::cout<<"\n";
> int b=7;
> b++; std::cout<<b;
> int c=7;
> ++c; std::cout<<"\n"<<c;
> //????????? why? same outputs!
> return 0;
> }
>
> _Same_output_.
> What's the difference?
> (I use these in a program, which doesn't crash....)
> ...


Both 'i++' and '++i' in C++ are _expressions_. Any non-void expression
in C++, has a result (i.e. what it evaluates to) and, possibly, some
side effects. When someone tells you that prefix increment happens
"before" and postfix increment happens "after", it really means that the
result of '++i' expression is the "new" value of 'i' (the value "after"
the increment), while the result of 'i++' expression is the "old" value
of 'i' (the value "before" the increment). This means that in order to
see the difference between '++i' and 'i++' you have to inspect the
_results_ of these expressions. The code you wrote does not use these
results in any way, it completely ignores them. No wonder you can't see
any difference.

To inspect the results of '++i' and 'i++' you have to store them and
output them later (or output them right away) instead of discarding
them. For example:

int i, a, b;

i = 0;
a = ++i; // store the result of pre-increment

i = 0;
b = i++; // store the result of post-increment

Now take a look at the values of 'a' and 'b' an you'll see the difference.

--
Best regards,
Andrey Tarasevich
  Réponse avec citation
Vieux 08/02/2008, 22h01   #6
Hans Mull
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

Andrey Tarasevich schrieb:
> John Brawley wrote:
>> ...
>> #include <iostream>
>>
>> int main() {
>> for(int i=0; i<10; i++)
>> std::cout<<i<<", ";
>> std::cout<<"\n";
>> for(int i=0;i<10;++i)
>> std::cout<<i<<", ";
>> std::cout<<"\n";
>> int b=7;
>> b++; std::cout<<b;
>> int c=7;
>> ++c; std::cout<<"\n"<<c;
>> //????????? why? same outputs!
>> return 0;
>> }
>>
>> _Same_output_.
>> What's the difference?
>> (I use these in a program, which doesn't crash....)
>> ...

>
> Both 'i++' and '++i' in C++ are _expressions_. Any non-void expression
> in C++, has a result (i.e. what it evaluates to) and, possibly, some
> side effects. When someone tells you that prefix increment happens
> "before" and postfix increment happens "after", it really means that the
> result of '++i' expression is the "new" value of 'i' (the value "after"
> the increment), while the result of 'i++' expression is the "old" value
> of 'i' (the value "before" the increment). This means that in order to
> see the difference between '++i' and 'i++' you have to inspect the
> _results_ of these expressions. The code you wrote does not use these
> results in any way, it completely ignores them. No wonder you can't see
> any difference.
>
> To inspect the results of '++i' and 'i++' you have to store them and
> output them later (or output them right away) instead of discarding
> them. For example:
>
> int i, a, b;
>
> i = 0;
> a = ++i; // store the result of pre-increment
>
> i = 0;
> b = i++; // store the result of post-increment
>
> Now take a look at the values of 'a' and 'b' an you'll see the difference.
>

You can directly print them via cout:
cout << ++i;
cout << i++;

Kind regards, Hans
  Réponse avec citation
Vieux 08/02/2008, 22h05   #7
Ioannis Vranos
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

John Brawley wrote:
> Please pardon a maybe very stupid question?
> I've read and reread Bjarne Stroustrup on this, and I still don't "get it,"
> so I wrote this to me understand, and now I _really_ don't "get it."
> Why, if one increments before, and the other after, do these snippets output
> exactly the same?
>
>
> #include <iostream>
>
> int main() {
> for(int i=0; i<10; i++)
> std::cout<<i<<", ";
> std::cout<<"\n";
> for(int i=0;i<10;++i)
> std::cout<<i<<", ";
> std::cout<<"\n";
> int b=7;
> b++; std::cout<<b;
> int c=7;
> ++c; std::cout<<"\n"<<c;
> //????????? why? same outputs!
> return 0;
> }
>
> _Same_output_.
> What's the difference?
> (I use these in a program, which doesn't crash....)



Along the answers of the others, my advice is, read a good introductory
C++ book cover to cover, before reading "The C++ Programming Language"
3rd Edition or Special Edition cover to cover.
  Réponse avec citation
Vieux 08/02/2008, 22h13   #8
Pascal Bourguignon
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

Hans Mull <deyringer@googlemail.com> writes:
> [...]
> You can directly print them via cout:
> cout << ++i;
> cout << i++;


Yes, but if you want to see non-puzzling results, you'd better use two
variables:

int i=0;cout<<"++i = "<<++i<<endl;
int j=0;cout<<"j++ = "<<j++<<endl;

--
__Pascal Bourguignon__ http://www.informatimago.com/
The mighty hunter
Returns with gifts of plump birds,
Your foot just squashed one.
  Réponse avec citation
Vieux 08/02/2008, 22h59   #9
John Brawley
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?


"John Brawley" <jgbrawley@charter.net> wrote in message
news:iL1rj.3497$TJ6.2165@newsfe02.lga...
> Please pardon a maybe very stupid question?
> I've read and reread Bjarne Stroustrup on this, and I still don't "get

it,"

<manisnips>

Andrey wrote:
.....it really means that the
result of '++i' expression is the "new" value of 'i' (the value "after"
the increment), while the result of 'i++' expression is the "old" value
of 'i' (the value "before" the increment). This means that in order to
see the difference between '++i' and 'i++' you have to inspect the
_results_ of these expressions. The code you wrote does not use these
results in any way, it completely ignores them. No wonder you can't see
any difference.

The first part of that is exactly what Bjarne said in the book.
He even gave examples, and I could not wrap mind (correctly) around it (as
evidenced by all of your ++most (*g*) ful code snippets, which I am
about to run).
The second part of that --having to _do_ something with them and then look
at the results-- was not clear in Bjarne's explanation.
I thought I had (done something with them).
Obviously not.
I have run across the difference in my actual program, but didn't understand
it then either: stepping through an array[]'s pockets, I'd get an out of
range error with one, but not with the other.

Thank you all very much.
Thread is sufficient I'm sure.
(I'll thank y'all even one more when I finally understand this permanently.)


--
Peace
JB
jb@tetrahedraverse.com
Web: http://tetrahedraverse.com







  Réponse avec citation
Vieux 08/02/2008, 23h36   #10
John Brawley
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?


"John Brawley" <jgbrawley@charter.net> wrote in message
news:iL1rj.3497$TJ6.2165@newsfe02.lga...
> Please pardon a maybe very stupid question?
> I've read and reread Bjarne Stroustrup on this, and I still don't "get

it,"

<manisnips>

........Boy, that is a _subtle_ difference for a newbie to "get"....

Mine:

int b=7; //declare b equal to 7
b++; std::cout<<b; //"leave b alone"; spit it
int c=7; //declare c equal to 7
++c; std::cout<<"\n"<<c; //"up c by one"; spit it
// same outputs (7,7); thinking _seemed_ straight!

Yours:

int b=7; //declare b equal to 7
cout << b++ <<endl; //do zip to b 1st, spit it unmodified
int c=7; //declare c equal to 7
cout << ++c << endl; //do zip to c 1st, spit it upped by 1
// output (7,8); --counterintuitive!

That's not an easy thing to grasp, despite the utter simplicity of the
example.
But I think I get it now; the other examples did something with the vars
before output, this does something with them _during_ output.

From this particular example, I don't feel _quite_ so stupid.
I have it now.
Much appreciated.

(Oh, one last: I do appreciate the recommendation to read a good book on C++
before reading "The C++ Programming Language," but I'm a 'handyman' not a
programmer, and I already have the 400+ line program written twice, once in
Python and now in C++. I found that "_the_ Source" (Stroustrup, in the case
of the C++) was my best bet in both languages. Toolboxes, not classrooms
and libraries, were what I really needed in both cases.)


--
Peace
JB
jb@tetrahedraverse.com
Web: http://tetrahedraverse.com




--
Peace
JB
jb@tetrahedraverse.com
Web: http://tetrahedraverse.com




  Réponse avec citation
Vieux 08/02/2008, 23h51   #11
acehreli@gmail.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

On Feb 8, 2:59 pm, "John Brawley" <jgbraw...@charter.net> wrote:
> Andrey wrote:
>
> the
> result of '++i' expression is the "new" value of 'i' (the value "after"
> the increment), while the result of 'i++' expression is the "old" value
> of 'i' (the value "before" the increment).


> (I'll thank y'all even one more when I finally understand this permanently.)


A common description of the differences between the two is

++i increments i before
i++ increments i after

Unfortunately that definition works only in C. There is a better
description that works in both languages:

++i increments i and uses i
i++ takes a copy of i, increments i, and uses the copy

Daniel T.'s recommendation of looking at the implementation is ful
in seeing this. So, here is how it boils down:

foo(++i) is the same thing as

++i;
foo(i);

On the other hand, foo(i++) is the same thing as

const int compiler_generated_temp = i;
++i;
foo(compiler_generated_temp);

Ali
  Réponse avec citation
Vieux 08/02/2008, 23h53   #12
Ioannis Vranos
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

John Brawley wrote:

>
> (Oh, one last: I do appreciate the recommendation to read a good book on C++


Actually: "A good *introductory* book on C++".

"The C++ Programming Language" 3rd Edition or Special Edition is an
excellent book itself, better suited to intermediate C++ programmers IMHO.
  Réponse avec citation
Vieux 08/02/2008, 23h58   #13
John Brawley
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?


"Ioannis Vranos" <ivranos@nospam.no.spamfreemail.gr> wrote in message
news:foiq23$t7a$2@ulysses.noc.ntua.gr...
> John Brawley wrote:
>
> >
> > (Oh, one last: I do appreciate the recommendation to read a good book on

C++
>
> Actually: "A good *introductory* book on C++".
>
> "The C++ Programming Language" 3rd Edition or Special Edition is an
> excellent book itself, better suited to intermediate C++ programmers IMHO.


I take your point, and would certainly agree, for any newbie who was trying
to *learn to program* in C++. However, my case was/is different: I was
trying (well, past tense; I've already succeeded) to *write a program* in
C++.
Those are actually, if you think about it, very different motivations
driving perhaps equally different paths and needs. Having never done so
before, one can pick up an oboe and in a while learn to play one piece (say,
"Stranger on the Shore" --Acker Bilk) on it rather indistinguishably from a
musician, but if asked to play a different piece, nothing but squawks might
emerge. (*g*)
I had *used* all this code to get something working. I didn't necessarily
_understand_ why or how it worked in every case (especially this ++i / i++
case), but no matter: the program does exactly what I wanted it to.


--
Peace
JB
jb@tetrahedraverse.com
Web: http://tetrahedraverse.com



  Réponse avec citation
Vieux 09/02/2008, 00h56   #14
Ioannis Vranos
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

John Brawley wrote:
> "Ioannis Vranos" <ivranos@nospam.no.spamfreemail.gr> wrote in message
> news:foiq23$t7a$2@ulysses.noc.ntua.gr...
>> John Brawley wrote:
>>
>>> (Oh, one last: I do appreciate the recommendation to read a good book on

> C++
>> Actually: "A good *introductory* book on C++".
>>
>> "The C++ Programming Language" 3rd Edition or Special Edition is an
>> excellent book itself, better suited to intermediate C++ programmers IMHO.

>
> I take your point, and would certainly agree, for any newbie who was trying
> to *learn to program* in C++. However, my case was/is different: I was
> trying (well, past tense; I've already succeeded) to *write a program* in
> C++.
> Those are actually, if you think about it, very different motivations
> driving perhaps equally different paths and needs. Having never done so
> before, one can pick up an oboe and in a while learn to play one piece (say,
> "Stranger on the Shore" --Acker Bilk) on it rather indistinguishably from a
> musician, but if asked to play a different piece, nothing but squawks might
> emerge. (*g*)
> I had *used* all this code to get something working. I didn't necessarily
> _understand_ why or how it worked in every case (especially this ++i / i++
> case), but no matter: the program does exactly what I wanted it to.



OK it is up to you to decide what you need, but if you had read a good
introductory C++ book, I think you would have understood the difference
between i++ and ++i in the first place. :-)
  Réponse avec citation
Vieux 09/02/2008, 02h08   #15
John Brawley
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?


"Ioannis Vranos" <ivranos@nospam.no.spamfreemail.gr> wrote in message
news:foitob$160c$1@ulysses.noc.ntua.gr...
> John Brawley wrote:
> > "Ioannis Vranos" <ivranos@nospam.no.spamfreemail.gr> wrote in message
> > news:foiq23$t7a$2@ulysses.noc.ntua.gr...
> >> John Brawley wrote:
> >>
> >>> (Oh, one last: I do appreciate the recommendation to read a good book

on
> > C++
> >> Actually: "A good *introductory* book on C++".
> >>
> >> "The C++ Programming Language" 3rd Edition or Special Edition is an
> >> excellent book itself, better suited to intermediate C++ programmers

IMHO.
> >
> > I take your point, and would certainly agree, for any newbie who was

trying
> > to *learn to program* in C++. However, my case was/is different: I was
> > trying (well, past tense; I've already succeeded) to *write a program*

in
> > C++.
> > Those are actually, if you think about it, very different motivations
> > driving perhaps equally different paths and needs. Having never done so
> > before, one can pick up an oboe and in a while learn to play one piece

(say,
> > "Stranger on the Shore" --Acker Bilk) on it rather indistinguishably

from a
> > musician, but if asked to play a different piece, nothing but squawks

might
> > emerge. (*g*)
> > I had *used* all this code to get something working. I didn't

necessarily
> > _understand_ why or how it worked in every case (especially this ++i /

i++
> > case), but no matter: the program does exactly what I wanted it to.

>
>
> OK it is up to you to decide what you need, but if you had read a good
> introductory C++ book, I think you would have understood the difference
> between i++ and ++i in the first place. :-)


Doubtless I would have.
Thank you for the kind advice.
I often play on grounds for which I am not qualified.
So far, no serious injuries....
(*grin*)


--
Peace
JB
jb@tetrahedraverse.com
Web: http://tetrahedraverse.com



  Réponse avec citation
Vieux 09/02/2008, 18h36   #16
James Kanze
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: i++ or ++i ?

On Feb 9, 12:51 am, acehr...@gmail.com wrote:
> On Feb 8, 2:59 pm, "John Brawley" <jgbraw...@charter.net> wrote:
> A common description of the differences between the two is


> ++i increments i before
> i++ increments i after


> Unfortunately that definition works only in C. There is a better
> description that works in both languages:


> ++i increments i and uses i
> i++ takes a copy of i, increments i, and uses the copy


And what's the difference between the two descriptions?

An expression has two characteristics: its side effects, and its
value. The side effects of the two expressions are the same.
The value is different. If you don't use the value, there's
(conceptually, at least) no value.

If you're writing a user defined ++, of course, and you want to
make it behave like the built in one (always a good idea), then
taking a copy before incrementing is usually the simplest way.

--
James Kanze (GABI Software) email:james.kanze@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
  Réponse avec citation
Réponse


Outils de la discussion

Règles de messages
Vous ne pouvez pas créer de nouvelles discussions
Vous ne pouvez pas envoyer des réponses
Vous ne pouvez pas envoyer des pièces jointes
Vous ne pouvez pas modifier vos messages

Les balises BB sont activées : oui
Les smileys sont activés : oui
La balise [IMG] est activée : oui
Le code HTML peut être employé : non
Trackbacks are oui
Pingbacks are oui
Refbacks are oui


Fuseau horaire GMT +1. Il est actuellement 17h37.


Édité par : vBulletin® version 3.7.3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0 RC5 Tous droits réservés.
Version française #16 par l'association vBulletin francophone
PHWinfo est un site Éducation Sans Frontières ©2000-2008
Ad Management by RedTyger
©Tous droits réservés par les parties respectives
Page generated in 0,29225 seconds with 24 queries