John Emmas wrote on 31 October 2008 12:35:

> ----- Original Message -----
> From: "Dave Korn"
> Sent: 31 October 2008 12:22
> Subject: RE: cygwin g++ strictness
>> 
>> You are creating temporaries here.  If AddTwoInts modifies either of the
>> int references it has, that will only change the temporaries; x and y
>> will /not/ be modified.
> 
> You'll be surprised if you try it Dave....

  Ah, I overlooked that you were using plain int32_t types in this example.
It wouldn't work with gints (in fact, contrary to what I said, the compiler
won't even create temps for you), not even if gint is a typedef for int32_t.
Your example requires gint to be a typedef for int.

  If gint is a typedef for long, and you make 'm' a gint as well as 'n', and
compile on a platform where longs are 64 bits and ints 32, the assignment to
'a' in AddTwoInts will overwrite both n and m in main (simulated here by
typedef'ing gint to long long on a 32-bit platform):


~ $ cat woo.cxx
#include <stdio.h>
typedef long long gint;

int AddTwoInts (int& a, int& b)
{
    int x = a;
    int y = b;

    a = 6;  // Note this line

    return x + y;
}

int main()
{
gint  m=4;
int  n=5;

    AddTwoInts ((int&)m, n);
    printf ("m is %d n is %d\n", m, n);

    return 0;  // 'm' equals 6 by the time you get to this line !!
}
@_______. .
(       /"\
 ||--||(___)
 '"  '"'---'
~ $ g++ woo.cxx -o woo
@_______. .
(       /"\
 ||--||(___)
 '"  '"'---'
~ $ ./woo.exe
m is 6 n is 0
@_______. .
(       /"\
 ||--||(___)
 '"  '"'---'
~ $


  That's why the casts are inadvisable.

  Add "--save-temps" to your compiler flags to get the preprocessed sources in
*.i or *.ii (for C or C++) files.


    cheers,
      DaveK
-- 
Can't think of a witty .sigline today....


--
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple
Problem reports:       http://cygwin.com/problems.html
Documentation:         http://cygwin.com/docs.html
FAQ:                   http://cygwin.com/faq/

Reply via email to