为什么我对值返回函数的调用不起作用?

问题描述 投票:-1回答:2

我试图确保我的函数原型和定义正确。编译器没有显示这些错误。而且我在教科书中进行了查找,以确保我正确编写了函数调用,但是仍然无法正常工作。我想念什么? (这里的编程非常新。请客气。)


#include <iostream>
using namespace std;

bool noNegatives(int intArray[], int arraySize);

int main()
{
    int mainArrSize = 5;
    int mainArr[] = {7, 12, 4, 69, -2};
    bool funcResult;

    funcResult = noNegatives(mainArr, mainArrSize); //Here's the call that wont work 


    if (funcResult = true)
          {
          cout << "The array did not contain any negative"
              << " integers." << endl;
          }
      else
          cout << "The array contained negative integers." << endl;

    return 0;
}

bool noNegatives(int intArray[], int arraySize)
{
    bool result = false;
    int index;

    for (index = 0; index < arraySize; index++)
        {
            cin >> intArray[index];
                if (intArray[index] < 0)
                    return false;
        }


    return result;
}
c++ function
2个回答
2
投票

实际上,编译器确实会对此行发出警告。

if (funcResult = true)

也许您想比较

if (funcResult == true)

始终至少使用-Wall进行编译,并认真对待您看到的所有警告。实际上,将它们视为错误。您甚至可以通过使用-Werror进行编译来强制执行此操作。


0
投票

1。启用警告,不要忽略它们。

这里,警告的重要部分是“注意:使用'=='将此赋值转换为相等比较”。 (注意:这是Clang提供的警告,其他编译器将具有不同的警告文本。所有编译器都会针对此错误发出警告。)

<source>:16:20: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
    if (funcResult = true)
        ~~~~~~~~~~~^~~~~~
<source>:16:20: note: place parentheses around the assignment to silence this warning
    if (funcResult = true)
                   ^
        (                )
<source>:16:20: note: use '==' to turn this assignment into an equality comparison
    if (funcResult = true)
                   ^
                   ==
1 warning generated.

2。同时创建和分配

这是您的代码:

    bool funcResult;

    funcResult = noNegatives(mainArr, mainArrSize); //Here's the call that wont work 

    if (funcResult = true)

我将同时声明和初始化变量。我会这样写:

    bool funcResult = noNegatives(mainArr, mainArrSize); //Here's the call that wont work 

    if (funcResult = true)

因为如果这样做,我也可以将变量设为const!然后,这个小错误将无法编译,这将更早地告诉我们有关该问题的信息。

    const bool funcResult = noNegatives(mainArr, mainArrSize); //Here's the call that wont work 

    if (funcResult = true) // Now this line won't compile anymore

3。使用C ++容器而不是C样式的数组

(int intArray[], int arraySize)签名很危险(内存不安全!),可以用std::vector<int>(如果大小在编译时不固定)或std::array<int, 5>(如果大小在编译时是已知的)替换。 -时间)。

完成此更改后,您的代码如下所示:

#include <iostream>
#include <vector>

bool noNegatives(std::vector<int> const &intArray) {
  bool result = false;

  for (int index = 0; index < intArray.size(); index++) {
    if (intArray[index] < 0)
      return false;
  }

  return result;
}

int main() {
  const std::vector<int> mainArr = {7, 12, 4, 69, -2};
  const bool funcResult =
      noNegatives(mainArr); // Here's the call that wont work

  if (funcResult == true) {
    std::cout << "The array did not contain any negative"
              << " integers.\n";
  } else {
    std::cout << "The array contained negative integers.\n";
  }
  return 0;
}

[此处有小改动:1.不要使用“使用命名空间标准”。2.将noNegatives的声明和定义移到同一位置,只是为了使其更简洁。3.请勿使用std::endl,而是使用\n + std::flush。并且在不需要std::flush的情况下,丢弃冲洗。4.如果某物是恒定的,则只需将其标记为不变。那只是个好习惯。在这种情况下,mainArr是恒定的。

4。使用现代的C ++基于范围的for循环

代替使用索引的原始数组访问,最好使用基于范围的循环。因此,我们将代码转换为:

  for (int index = 0; index < intArray.size(); index++) {
    if (intArray[index] < 0)
      return false;
  }

进入此:

  for (int value: intArray) {
    if (value < 0)
      return false;
  }

5。可选:使用std::all_of

C ++ 11及更高版本提供了许多出色的算法,因此您不必编写自己的算法。您正在检查容器中所有元素的条件(“为正”)是否成立。

为此,std::all_of存在。

[包含<algorithm>之后,我们可以使noNegatives函数成为一行:

bool noNegatives(std::vector<int> const &intArray) {
  return std::all_of(array.begin(), array.end(), [](int x) { return x >= 0.; });
}

[[](int x) { return x >= 0.; }lambda function,并定义一个函数,该函数接受int x,然后返回它是否为正。

6。可选:摆脱iostreams

std::cout在编译时会产生很多额外的代码。对于固定字符串,可以使用puts("Hello\n");中的#include <cstdio>。一个更通用的解决方案是使用fmt,但您必须在系统上安装它。

fmt变为std::cout << "The array contained negative integers.\n";

最终结果:

puts("The array contained negative integers.\n");

https://godbolt.org/z/4FVyOw

注意,我用#include <algorithm> #include <array> #include <vector> #include <cstdio> int main() { const std::array<int, 5> mainArr {7, 12, 4, 69, -2}; const bool allPositive = std::all_of(mainArr.begin(), mainArr.end(), [](int x) { return x >= 0.; }); if (allPositive) { puts("The array did not contain any negative integers.\n"); } else { puts("The array contained negative integers.\n"); } return 0; } 替换了vector<int>,因为这样编译器可以将其优化为零。这是生成的汇编代码:

std::array<int, 5>
© www.soinside.com 2019 - 2024. All rights reserved.