-1

Why am I not getting an error even if I declared a function without a type?

If the return type is accepted as some types by default, is it healthy to write codes like this?

If it already works like this with a compiler feature, then why would we even need to write void for functions?

Note: I am using Code::Blocks that has a gnu compiler that follows c++11 std if it has anything to do with it.

#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;
    }

}
noob
  • 107
  • 6

2 Answers2

2

Why does this function without a type still work?

The program is ill-formed in standard C++.

In some old versions of C, type declarations were optional, and the type was int by default. C compiler(s) have kept this "feature" as a language extension. Those C compiler(s) have become C++ compilers, and still have kept the language extension.

In addition to being ill-formed, your program also has undefined behaviour because the function that was implicitly - through the language extension - declared to return int fails to return any value.


is it healthy to write codes like this?

No.

I am using ... gnu compiler

You can ask GCC to conform to the standard by using the -pedantic option. You can ask GCC to fail compilation when the program is ill-formed by using the -pedantic-errors option - although that may be overridden by the -fpermissive option, so be careful to not use that.

eerorika
  • 232,697
  • 12
  • 197
  • 326
2

In C++ it's wrong to declare a function without a type in accordance with ISO C ++, but you can ignore this error using the "-fpermissive" flag. Your compiler is likely to use this flag to ignore standard coding errors downgrading them to warnings. You should always use at least the void type when declaring functions so your code comply with the standards and can be understandable by every programmer and compilers.

Yorfrank Bastidas
  • 304
  • 1
  • 3
  • 11