Re: operator <<
From: Carl Daniel [VC++ MVP] (cpdaniel_remove_this_and_nospam_at_mvps.org.nospam)
Date: 07/19/04
- Next message: P.J. Plauger: "Re: Sockets and filebuf with msvc 2003"
- Previous message: Jeff F: "Re: delete iterator inside while loop"
- In reply to: news.microsoft.com: "operator <<"
- Next in thread: tom_usenet: "Re: operator <<"
- Reply: tom_usenet: "Re: operator <<"
- Messages sorted by: [ date ] [ thread ]
Date: Mon, 19 Jul 2004 07:11:24 -0700
"news.microsoft.com" <hovhannes.asatryan@epygilab.am> wrote in message
news:%23gDyw9YbEHA.3792@TK2MSFTNGP09.phx.gbl...
> Hi all.
>
> I have written the following code.
>
> void main()
> {
> int y = 1;
> cout << "a = " << y << endl << "b = " << y++ << endl << "c = " << y++ <<
> endl;
>
> }
>
> and get the following result
>
> a = 3
> b = 2
> c = 1
>
> who can explain what's going on?
Simple: your code has unspecified behavior according to the C++ standard.
In your code, the call to cout transalates to:
operator <<(
operator <<(
operator <<(
operator <<(
operator <<(
operator <<(
operator <<(cout,"a="),y),"b="),y++),"c="),y++),endl);
after resolution of user-defined operator overloading. Now, the order in
which the argument to operator << are evaluated is not specified. Look at
the second level nesting: it's not defined whethery++ or the third-level
nested call to operator << is evaluated first. etec.
So technically, the 3 references to y could occur in any order, in could
vary from compiler to compiler, id could vary from debug build to release
build, it could vary from one compilation to the next. In practice, you'll
either get the ordering you saw or the ordering you expected, but you're not
guaranteed to get either: 2 1 3 is equally valid output.
-cd
- Next message: P.J. Plauger: "Re: Sockets and filebuf with msvc 2003"
- Previous message: Jeff F: "Re: delete iterator inside while loop"
- In reply to: news.microsoft.com: "operator <<"
- Next in thread: tom_usenet: "Re: operator <<"
- Reply: tom_usenet: "Re: operator <<"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|