Re: operator <<

From: Carl Daniel [VC++ MVP] (cpdaniel_remove_this_and_nospam_at_mvps.org.nospam)
Date: 07/19/04


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



Relevant Pages

  • Re: fields for methods?
    ... void A::foo{ ... but only by a compiler that is allowed to ... int static_instance i = 0; ... it totally breaks the idea of encapsulation, which is the reason a lot ...
    (comp.programming)
  • Re: fields for methods?
    ... but only by a compiler that is allowed to ... struct A {void foo();}; ... int static_instance i = 0; ... Is not possible because foo is the only member of A... ...
    (comp.programming)
  • Re: Calling a matlab dll in java
    ... I compiled it with mcc to dll shared library ... all compiler and linker options in VS took me a while, ... JNIEXPORT void JNICALL Java_JNITest_JNITest_initializeApplication ... public void launchThread() ...
    (comp.soft-sys.matlab)
  • Re: Determining a functions calling address
    ... >> conversion between pointer to any type of function and pointer to ... >> void, or indeed pointer to any other object type. ... Apparently you are not using a real C++ compiler, ... First you should have received diagnostics along these lines: ...
    (comp.lang.cpp)
  • Re: Calling a matlab dll in java
    ... you mention about putting a -nojvm option when initializing the dll ... the matlab generated library inside my jni-dll) ... all compiler and linker options in VS took me a while, ... JNIEXPORT void JNICALL ...
    (comp.soft-sys.matlab)