C++ | main function error | beginners [duplicate]

只谈情不闲聊 提交于 2019-12-02 06:48:21

问题


I'm totally new with c++ and I'm using eclipse.

but... I don't know why I get this error at the main function:

ERROR: ::main must return int

My code is:

void main()
{
char a;
while (a!='q')
{
    string ln = "enter option: ";
    cout<< ln;

    switch(a)
    {
    case 1:
        if (a=='1')
            func1();
        break;
    case 2:
        if (a=='2')
            break;
        break;
    }
}
}

回答1:


Because in C++, the main function must have a return type of int.

Your version with a return type of void is incorrect and is being correctly rejected by your compiler.

Just change the declaration from

void main()

to

int main()

There is an alternative form that allows you to process arguments passed on the command line to your program. It looks like this:

int main (int argc, char *argv[])

but when you're just learning C++ and trying to print "hello world" on the screen, this is probably not something you need to worry about. You'll get there eventually.

And consider updating the book you're using to learn C++, too. If it's getting the function signature of the entry point wrong, what other more complicated things might it also be getting wrong?! No point in learning the language wrong the first time around. A list of suggested books is available here.




回答2:


You have to change your void main() to int main().

You can't have a main function without any return in C++.




回答3:


char a;
while (a!='q')

You are comparing an uninitialized variable with the letter q. Reading from an uninitialized variable invokes undefined behavior. If you're unlucky, a!='q' might be false. Change char a; to char a = 0; (or any other non-q value) or replace the while loop with a do-while loop.




回答4:


The return type should be int:

int main (void)

int main (int argc, char *argv[])



来源:https://stackoverflow.com/questions/9654601/c-main-function-error-beginners

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!