optimization and printf for i386-pc-solaris-2.7

Jonathan Hamaker hamaker@isip.msstate.edu
Fri May 11 06:11:00 GMT 2001


In the code included below, the two code segments in main() are identical
except one has an extra print statement in it. However, depending on the
optimization mode, the results of the subtraction (z1, z2) are different!!!

The specs are below. I can understand how pipelining can change the order
of operations but I don't see how a print statement can change the way that
subtraction is executed. Further, if I remove any of the print statements
in the file then the debug and optimize versions of the code produce the 
same values.

I suppose we can work around this, but I'm interested to know when and why
this behavior occurs and how we can design around it in the future. 
Getting identical final results on debug and optimize is very helpful if it
is possible - and I would think that subtraction would be stable to 
pipelining. Any help or insight would be greatly appreciated

Thank you,

Jon Hamaker
Institute for Signal and Information Processing
Mississippi State University
hamaker@isip.msstate.edu

Here are the specs: 

isip109_[1]: uname -a 
SunOS isip109.isip.msstate.edu 5.7 Generic_106542-12 i86pc i386

isip109_[1]: gcc --version
2.95.2

isip109_[1]: gcc -g -o x.exe x.cc
isip109_[1]: ./x.exe 
z1 =     7.99999982118606567383e-02
x2_copy =     1.00000001490116119385e-01
y2_copy =      1.99999995529651641846e-02
z2 =     7.99999982118606567383e-02

*** z1 and z2 are identical ***

isip109_[1]: gcc -O2 -o x.exe x.cc
isip109_[1]: ./x.exe 
z1 =     8.00000019371509552002e-02
x2_copy =     1.00000001490116119385e-01
y2_copy =      1.99999995529651641846e-02
z2 =     7.99999982118606567383e-02

*** z1 and z2 are different ***


#include <math.h>
#include <stdio.h>

class Float {

protected:
  float value_d;

public:

  // method: destructor
  //
  ~Float() {}
  
  // method: default constructor
  //
  Float(float arg = 0.0) {
    value_d = arg;
  }

  // method: operator TIntegral()
  //
  operator float() const {
    printf("");
    return value_d;
  }

  // method: operator=
  //
  Float& operator= (float arg) {
    value_d = arg;
    return *this;
  }
};

int main() {

  Float x1 = 0.1f;
  float x1_copy = x1;
  Float y1 =  0.02f;
  float y1_copy = y1;
  float z1 = (float)((float)x1_copy - (float)y1_copy);
  printf("z1 = %30.20e\n", z1);


  Float x2 = 0.1f;
  float x2_copy = x2;
  Float y2 =  0.02f;
  float y2_copy = y2;
  float z2 = (float)((float)x2_copy - (float)y2_copy);
  printf("x2_copy = %30.20e\ny2_copy =  %30.20e\n", x2_copy, y2_copy);
  printf("z2 = %30.20e\n", z2); 

  return 1;
}



More information about the Gcc-bugs mailing list