简体   繁体   English

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

[英]Accumulative return value for non-static variable?

I ran into unexpected behavior with a function I wrote to compute the average point for a set of 3D points. 我使用编写的函数计算一组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 );
  // ...
}

For each iteration the return value of average_vertex_position would accumulate unless I added explicitly the initialization Point3d average = { 0.0, 0.0, 0.0 }; 对于每次迭代,除非我明确添加了初始化Point3d average = { 0.0, 0.0, 0.0 };否则average_vertex_position的返回值将累积Point3d average = { 0.0, 0.0, 0.0 }; .

If the previous return value was Point3d( 10, 0, 20 ) and the next run should have returned Point3d( 20, 10, 0 ) it would instead return an accumulated result Point3d( 30, 10, 20 ) . 如果前一个返回值是Point3d( 10, 0, 20 ) ,而下一次运行应返回Point3d( 20, 10, 0 ) ,它将返回累积结果Point3d( 30, 10, 20 )

Originally I had just Point3d average; 最初我只有Point3d average; assuming all the member values ( double values) would be initialized to 0.0. 假设所有成员值( double值)都将初始化为0.0。 I also assumed average would be in this initial state between each call. 我还假设average将在每次调用之间处于此初始状态。 I don't understand why I need to explicitly initialize it? 我不明白为什么需要显式初始化它?

I trimmed out the code I didn't think was relevant - but I could be wrong, in which case I'll update if it doesn't hold enough information. 我删节了我认为不相关的代码-但是我可能错了,在这种情况下,如果没有足够的信息,我将进行更新。

That is normal with auto variables - they are not initialized to 0 if not explicitly stated. 对于auto变量,这是正常现象-如果未明确说明,则不会将其初始化为0。

The fact that the old values are reused is pure coincidence, as you don't have any other function calls in-between. 重用旧值的事实纯属巧合,因为它们之间没有任何其他函数调用。 If you would have them, the memory at the given stack position would be overwritten and your values were different. 如果要使用它们,则给定堆栈位置的内存将被覆盖,并且您的值将不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM