the usual conversions

  • Follow


I found this issue here with gcc 3.4.1 and I'm unsure about it: 

#include <iostream>
using namespace std; 

int f0(int x) 
{
  int k=1000000; 
  return (x*1000000)/1000000; 
}
int f1(int x) 
{
  const int k=1000000; 
  return (x*k)/k; 
}
int f2(int x) 
{
  int k=1000000; 
  return (x*k)/k; 
}

int main() 
{
  cout << f0(10000) << endl; 
  cout << f1(10000) << endl; 
  cout << f2(10000) << endl; 
}

The output of this is when compiled (even without optimizations) is:

10000
10000
1410

GCC uses the equation (K*x)/K=x to fold the expressions with *constant*
K, giving different output, because the overflow does not occur[1]. 

Did I overlook anything that could justify this behaviour? Or is it just
dead wrong, as I think, because it omits the "ususal conversions"?  

Marco

[1] No problem here, if x was declared as a small type, where x *
1000000 could not possibly overflow.



      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Reply Marco 7/27/2004 4:32:56 PM

On 27 Jul 2004 12:32:56 -0400, Marco Manfredini <nospam@phoyd.net>
wrote:

>I found this issue here with gcc 3.4.1 and I'm unsure about it: 
>
>#include <iostream>
>using namespace std; 
>
>int f0(int x) 
>{
>  int k=1000000; 
>  return (x*1000000)/1000000; 
>}
>int f1(int x) 
>{
>  const int k=1000000; 
>  return (x*k)/k; 
>}
>int f2(int x) 
>{
>  int k=1000000; 
>  return (x*k)/k; 
>}
>
>int main() 
>{
>  cout << f0(10000) << endl; 
>  cout << f1(10000) << endl; 
>  cout << f2(10000) << endl; 
>}
>
>The output of this is when compiled (even without optimizations) is:
>
>10000
>10000
>1410

That seems correct (as would any other output).

>GCC uses the equation (K*x)/K=x to fold the expressions with *constant*
>K, giving different output, because the overflow does not occur[1]. 
>
>Did I overlook anything that could justify this behaviour? Or is it just
>dead wrong, as I think, because it omits the "ususal conversions"?  

All three functions have signed int overflow, therefore all three have
undefined behaviour and can validly output anything at all or just
crash your computer.

Tom

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Reply tom_usenet 7/28/2004 2:26:56 AM


Marco Manfredini wrote:
> GCC uses the equation (K*x)/K=x to fold the expressions with *constant*
> K, giving different output, because the overflow does not occur[1].

Overflow on signed arithmetic is undefined behavior.

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Reply Hyman 7/28/2004 2:54:27 AM

2 Replies
109 Views

(page loaded in 0.048 seconds)

5/19/2013 11:31:21 PM


Reply: