为什么没有类型的该功能仍然有效?

时间:2020-05-25 02:07:09

标签: c++ function-declaration

为什么即使我声明了没有类型的函数,我也不会收到错误消息?

如果默认情况下将返回类型接受为某些类型,那么编写这样的代码是否健康?

如果它已经具有编译器功能,那么为什么还要为函数编写 void 呢?

注意:我使用的是Code :: Blocks,它具有gnu编译器,该编译器遵循c ++ 11 std(如果与此有任何关系)。

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

ProfitDetermine (string str="")
{
    int profit=0, outcome=0, income=0, sales=0;
    int numberofhc=10, insur=1000000, hccost=2000000, price=3000000;
    stringstream (str) >> sales;

    outcome = (numberofhc * (insur + hccost));
    income = (sales*price);
    profit = income - outcome;
    cout << "profit is " << profit <<endl;

    if (profit < 0)
        cout << "lost\n";
    else if (profit==0)
        cout << "even\n";
    else
        cout << "profit\n";
}

int main()
{
    string sales="";
    cout << "enter the number of sales\n";
    getline(cin,sales);
    stringstream (sales) >> sales;

    while (sales!="quit") {
    ProfitDetermine(sales);
    cout << "\n\nEnter the number of sales\n";
    cin >> sales;
    }

}

2 个答案:

答案 0 :(得分:2)

为什么没有类型的该功能仍然有效?

程序是标准C ++格式的。

在某些旧版本的C中,类型声明是可选的,默认情况下,类型为int。 C编译器将此“功能”保留为语言扩展。这些C编译器已经成为C ++编译器,并且仍然保留了语言扩展名。

除了格式不正确之外,您的程序还具有未定义的行为,因为通过语言扩展被声明为返回int隐式函数无法返回任何值。


编写这样的代码是否健康?

否。

我正在使用... gnu编译器

您可以使用-pedantic选项要求GCC符合标准。您可以通过使用-pedantic-errors选项让GCC在程序格式错误时使编译失败-尽管-fpermissive选项可能会覆盖GCC,所以请小心不要使用它。

答案 1 :(得分:2)

在C ++中,根据ISO C ++声明没有类型的函数是错误的,但是您可以使用“ -fpermissive”标志忽略此错误。您的编译器可能会使用此标志来忽略将其降级为警告的标准编码错误。声明函数时,应始终至少使用void类型,以便您的代码符合标准,并且每个程序员和编译器都可以理解。

相关问题