-1

I am currently using Putty virtual machine (UNIX) for my class, and we are doing a short C++ assignment. The assignment is to: "Create a C++ program that tests to see if the file accounts exists and prints a message to say whether the file exists"

This is what I have, but when I try to compile the code, I get this error: error: ‘::main’ must return ‘int’

#include<iostream>
#include<fstream>

using namespace std;
inline bool exists_test1 (const std::string& name) {

if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}

void main()
{
string s;
cout<<"Enter filename";
cin>>s;
bool ans =exists_test1(s);
if(ans)
{
cout<<"File Exist"<<endl;
}
else
{
cout<<"File Does not Exist";
}
}
Migro96
  • 59
  • 1
  • 1
  • 8
  • 4
    What is your question? That error message seems entirely self-explanatory to me. – David Schwartz Dec 05 '16 at 03:50
  • PuTTY is a terminal emulator, not a virtual machine. You haven't shown us your entire program; what you've shown us wouldn't produce that error messages, since the compiler will choke on the syntax errors before it gets to `main`. Code should be properly indented. – Keith Thompson Dec 05 '16 at 04:00

1 Answers1

5

The return type of main is int. This is defined by the C++ standard. In my local copy of the C++11 draft it's outlined in § 3.6.1 Main Function :

  1. An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

    int main() { /* ...  */ }
    

    and

    int main(int argc, char* argv[]) { /* ...  */ }
    

Therefore your program is ill-formed according to the standard, and you compiler is rightly reporting it as an error. Define your function instead as:

int main()
{
    // your code...

    return 0;
}
paddy
  • 60,864
  • 6
  • 61
  • 103
  • I'll add that item 5 of that same section states _"If control reaches the end of main without encountering a return statement, the effect is that of executing `return 0;`"_ ... But your compiler should warn you about it, and the warning may be treated as an error. Get into the habit of always putting `return 0;` explicitly at the end of `main`. Or indeed return a value of your choice (but `0` is a convention that indicates success). – paddy Dec 05 '16 at 04:07