C++ 传递未初始化的变量

标签 c++ runtime initialization

当我到达网格末尾时,我需要在 C++ 中忽略一个未初始化的变量。

         pointMapIt++;
         float nextPointRow;
         if (pointMapIt != grid.points.end())
         {
             nextPointRow = 3.0;
             pointMapIt--;
         }

         if (point.dr != nextPointRow)
             //Do stuff

pointMap是一个遍历我的网格点的迭代器。它会在每次迭代时检查 nextPointRow。该程序将在最后一次迭代时崩溃,因为 nextPointRow 尚未设置。

我无法将 nextPointRow 设置为 0.0,因为 0.0 是实际有效的输入。事实上,我真的不知道 nextPointRow 会是什么。所以我真正需要的是能够(将 nextPointRow 初始化为并)检查 nextPointRow 是否为 NULL,如下所示:

         if (nextPointRow != null && point.dr != nextPointRow)

有什么方法可以做到这一点或完全规避这个问题吗?

最佳答案

最简单的可能是将 nextPointRow 设置为 NAN .

或者,在 nextPointRow 旁边设置一个 bool 标志,指示后者是否包含有效值。

另一种选择是像这样重新排列代码:

     pointMapIt++;
     if (pointMapIt != grid.points.end())
     {
         float nextPointRow = 3.0;
         pointMapIt--;
         if (point.dr != nextPointRow) {
             //Do stuff

关于C++ 传递未初始化的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14611943/

相关文章:

c++ - 如何在 C++ 中连接两个字符串 *arr[]

delphi - 如何在不启用使用运行时包构建的情况下使用 Delphi Dlls

Swift 如何将 `struct` 的默认初始值设定项设为私有(private)

c++ - 在 C++ 中使用指针的变量值及其地址

c++ - 如何在 C++ 中将命令行参数的整个集合(char**)作为只读传递?

java - 如何在javaFx中的应用程序窗口之前制作加载场景?

algorithm - 使用大 O 表示法计算算法的运行时间

C++静态数据成员初始化

c++ - vs2010中的 vector 初始化

C++设计——网络数据包和序列化