非静态变量的累计返回值?

时间:2012-03-12 12:49:50

标签: c

我使用我编写的函数遇到了意外行为,以计算一组3D点的平均点。

static inline Point3d
average_vertex_position( Vertex vertices[], int nPoints )
{
  Point3d average = { 0.0, 0.0, 0.0 }; // Must be there to avoid accumulation
  Point3d point;
  int i;

  for ( i = 0; i < nPoints; i++ )
  {
    point = vertices[i].position;
    average.x += point.x;
    average.y += point.y;
    average.z += point.z;
  }

  average.x /= (double) nPoints;
  average.y /= (double) nPoints;
  average.z /= (double) nPoints;

  return average;
}



// ...
Point3d average;
// ...
for ( j = i; j < nVertices; j++ )
{
  // ...
  average = average_vertex_position( vertices, nVertices );
  // ...
}

对于每次迭代,average_vertex_position的返回值将累积,除非我明确添加了初始化Point3d average = { 0.0, 0.0, 0.0 };

如果之前的返回值为Point3d( 10, 0, 20 )且下一次运行应返回Point3d( 20, 10, 0 ),则会返回累积结果Point3d( 30, 10, 20 )

最初我只有Point3d average;假设所有成员值(double值)都将初始化为0.0。我还假设average在每次调用之间都处于这种初始状态。我不明白为什么我需要明确初始化它?

我删除了我认为不相关的代码 - 但我可能错了,在这种情况下,如果它没有足够的信息,我会更新。

1 个答案:

答案 0 :(得分:3)

auto变量是正常的 - 如果没有明确说明,它们不会初始化为0.

重复使用旧值这一事实纯属巧合,因为您之间没有任何其他函数调用。如果你有它们,给定堆栈位置的内存将被覆盖,你的值也不同。

相关问题