c++ - 函数内部cout无法使用
阿神
阿神 2017-04-17 15:33:57
0
1
1358

平台:win10+vs2017
代码1:

#include<iostream>
#include<cstdio>
using namespace std;
int nice(int p, int e, int i, int d) {
    int k = d + 1;
    while ((k % 33) != 0)
    {
        ++k;
    }
    for (; k < 21252; k += 33)
    {
        if (((k - p) % 23 == 0) && ((k - e) % 28 == 0))
            return (k - d);
    }
}
int main()
{
    cout << nice(0, 0, 0, 0) << endl;
    system("pause");
    return 0;
}

执行成功。
如果我把nice函数中if语句块的return变成cout,再将函数返回类型变成void。程序不执行该语句。
代码如下:

#include<iostream>
#include<cstdio>
using namespace std;
void nice(int p, int e, int i, int d) {
    int k = d + 1;
    while ((k % 33) != 0)
    {
        ++k;
    }
    for (; k < 21252; k += 33)
    {
        if (((k - p) % 23 == 0) && ((k - e) % 28 == 0))
            cout << (k - d) << endl;
    }
}
int main()
{
    nice(0, 0, 0, 0);
    system("pause");
    return 0;
}

请问这是什么原因呢?我第一个代码执行成功不就表示程序逻辑正确并且可以执行到if的语句体吗?为什么把return改成cout语句以后就失败了呢?

阿神
阿神

闭关修行中......

reply all(1)
迷茫

Because the if branch has not been executed.

int nice(int p, int e, int i, int d) {
  int k = d + 1;
  while ((k % 33) != 0)
  {
    ++k;
  }
  for (; k < 21252; k += 33)
  {
    if (((k - p) % 23 == 0) && ((k - e) % 28 == 0))
      return (k - d);
  }
  return -1;
}

Replace the nice in your example 1 with the nice I provided (I just added return -1; at the end without modifying other parts), and the program output will be -1. This shows that the if branch has not been executed, otherwise the function will return early. (The least common multiple of 33, 23 and 28 is 21252, but for will ensure that every time it enters the loop body, k is less than 21252.)

The code in your example 1 causes undefined behavior. The result is usually an inexplicable value returned. And this value may be the value you expect.

If you look carefully, vs2017 will report a warning:

Warning C4715 'nice': not all control paths return a value

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template