Ошибка main must return int

This my main function:

void main(int argc, char **argv)
{
    if (argc >= 4)
    {
        ProcessScheduler *processScheduler;
        std::cout <<
            "Running algorithm: " << argv[2] <<
            "nWith a CSP of: " << argv[3] <<
            "nFilename: " << argv[1] <<
            std::endl << std::endl;

        if (argc == 4)
        {
            processScheduler = new ProcessScheduler(
                argv[2],
                atoi(argv[3])
            );
        }
        else
        {
            processScheduler = new ProcessScheduler(
                argv[2],
                atoi(argv[3]),
                atoi(argv[4]),
                atoi(argv[5])
            );
        }
        processScheduler -> LoadFile(argv[1]);
        processScheduler -> RunProcesses();

        GanntChart ganntChart(*processScheduler);
        ganntChart.DisplayChart();
        ganntChart.DisplayTable();
        ganntChart.DisplaySummary();

        system("pause");

        delete processScheduler;
    }
    else
    {
        PrintUsage();
    }
}

The error I get when I compile is this:

Application.cpp:41:32: error: ‘::main’ must return ‘int’

It’s a void function how can I return int and how do I fix it?

Michael's user avatar

Michael

3,0637 gold badges37 silver badges82 bronze badges

asked Nov 2, 2016 at 14:05

SPLASH's user avatar

3

Try doing this:

int main(int argc, char **argv)
{
    // Code goes here

    return 0;
}

The return 0; returns a 0 to the operating system which means that the program executed successfully.

answered Nov 2, 2016 at 14:07

Michael's user avatar

MichaelMichael

3,0637 gold badges37 silver badges82 bronze badges

5

C++ requires main() to be of type int.

roottraveller's user avatar

answered Nov 2, 2016 at 14:18

Nick Pavini's user avatar

Nick PaviniNick Pavini

3023 silver badges14 bronze badges

3

Function is declared as int main(..);, so change your void return value to int, and return 0 at the end of the main function.

answered Nov 2, 2016 at 14:14

renonsz's user avatar

renonszrenonsz

5711 gold badge4 silver badges17 bronze badges

  • Forum
  • Beginners
  • ‘main’ must return ‘int’

‘main’ must return ‘int’

Hey there

Whenever I compile this (see below) with gcc on Cygwin it returns with:
test.cpp:25: error: ‘main’ must return ‘int’;

Here is the source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <string>

// Use the standard namespace
using namespace std;

// Define the question class
class Question {
private:
  string Question_Text;
  string Answer_1;
  string Answer_2;
  string Answer_3;
  string Answer_4;
  int Correct_Answer;
  int Prize_Amount; //How much the question is worth
public:
  void setValues (string, string, string, string, string, int, int);
};

void main() {
  // Show the title screen
  cout << "****************" << endl;
  cout << "*The Quiz Show*" << endl;
  cout << "By Peter" << endl;
  cout << "****************" << endl;
  cout << endl;

  // Create instances of Question
  Question q1;

  // Set the values of the Question instances
  q1.setValues("What does cout do?", "Eject a CD", "Send text to the printer", "Print text on the screen", "Play a sound", 3, 2500);

}

// Store values for Question variables
void Question::setValues (string q, string a1, string a2, string a3, string a4, int ca, int pa) {
  Question_Text = q;
  Answer_1 = a1;
  Answer_2 = a2;
  Answer_3 = a3;
  Answer_4 = a4;
  Correct_Answer = ca;
  Prize_Amount=pa;

}

The error message is trying to tell you that main must return int.

i.e. Line 21 should be int main() and at the end of your program you must return 0; // obviously only if the program executed successfully

return 0; is superfluous — main (and only main) returns 0 by default when the end of the function is reached.

For people who are new to programming who may not know that it is a good habbit to get into. Also, although somwhat a small amount, it makes the code more readable.

This can be confusing since some compilers allow void main() and you see examples that use it in books and on the web ALL the time (by people who should know better). By the official rules of C++ though, it is wrong.

Topic archived. No new replies allowed.

>>‘::main’ must return ‘int’

тут компилятор в качестве К.О. указывает, что main() по стандарту должна возвращать int

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от alex_custov 05.09.10 00:04:16 MSD

Ответ на:

комментарий
от sudo-s 05.09.10 00:07:11 MSD

#include <iostream>
using namespace std;
int main ()
{
cout << «text»;
cin.get();
return 0;
}

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от Heretique 05.09.10 00:07:38 MSD

Ответ на:

комментарий
от sudo-s 05.09.10 00:11:04 MSD

return 0; не обязательно.

Booster ★★

(05.09.10 11:31:34 MSD)

  • Ссылка

Ответ на:

комментарий
от sudo-s 05.09.10 00:07:11 MSD

Вы когда-нибудь поймёте, что вторую строчку лучше трогать)))

return 0; не обязательно.

Да, кстати, стандарт одобряэ ) Справедливо только для main.

  • Ссылка

#include <iostream> 
#include <cstdlib> 
 
using namespace std; 
 
int main() 
{ 
cout << "text"; 
cin.get(); 
return EXIT_SUCCESS; 
}

unisky ★★

(05.09.10 12:53:40 MSD)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от unisky 05.09.10 12:53:40 MSD

Ответ на:

комментарий
от m4n71k0r 05.09.10 13:48:33 MSD

дооо…ещё cstdlib туда лепить)))))

более академично: влияет только на препроцессор, что при современных процессорах не имеет значения, ничего лишнего не линкуется же… и вдруг через полсотни лет, когда уже все забудут про цпп, кто-то задастся вопросом — почему именно 0
^_^

unisky ★★

(05.09.10 15:08:14 MSD)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от sudo-s 05.09.10 00:11:04 MSD

И тут я понял, чем не угодил kdevelop из соседнего топика.

Pavval ★★★★★

(05.09.10 16:58:56 MSD)

  • Ссылка

Ответ на:

комментарий
от unisky 05.09.10 15:08:14 MSD

Ну лично я собираюсь через 50 лет программировать нанитов и манипулировать генами. … если конечно ресурсы планеты не закончатся и наша цивилизация не войдёт в тёмную эпоху деградации и развитого каннибализма )))

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от m4n71k0r 05.09.10 18:03:57 MSD

> Ну лично я собираюсь через 50 лет программировать нанитов и манипулировать генами. … если конечно ресурсы планеты не закончатся и наша цивилизация не войдёт в тёмную эпоху деградации и развитого каннибализма )))

на D++? =)

korvin_ ★★★★★

(05.09.10 18:46:27 MSD)

  • Ссылка

Ответ на:

комментарий
от annulen 05.09.10 18:47:28 MSD

это g++ написанный на elisp, очевидно же!

  • Ссылка

Ответ на:

комментарий
от annulen 05.09.10 18:47:28 MSD

G++ — сокращение от GNU C++. Пишем в Емаксе, сохранием в цпп, потом g++ /path/to/file/filename и получаем бинарник.

sudo-s

(06.09.10 03:44:46 MSD)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от sudo-s 06.09.10 03:44:46 MSD

и получаем бинарник.

А если мне кроскомпилировать нужно? g++ [path/to/file] уже не прокатит (даже в емаксе) :)

quasimoto ★★★★

(06.09.10 10:37:38 MSD)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от quasimoto 06.09.10 10:37:38 MSD

>g++ [path/to/file] уже не прокатит

o rly? заменяешь g++ на имя твоего кросс-компилятора, и все дела

annulen ★★★★★

(06.09.10 11:15:41 MSD)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от annulen 06.09.10 11:15:41 MSD

Ну я как-то привык в ключиках всё писать — в Makefile-ах.

quasimoto ★★★★

(06.09.10 11:17:59 MSD)

  • Ссылка

Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.

The error message is trying to tell you that main must return int. return 0; is superfluous – main (and only main) returns 0 by default when the end of the function is reached. For people who are new to programming who may not know that it is a good habbit to get into.

Does main have to return int?

The main function should always return an int. In environments that have an operating system (OS), the OS starts your program running. The integer value returned from main provides a way for your program to return a value to the OS indicating whether the program succeeded, failed, or generated some integer result.

Does main return int in C?

void main(void) : It denotes empty, it means no value is returned which is also accepted in our programming language. 2. int main() : It return some value like Zero or Non-Zero. The main function is C always return an integer value and it goes as an exit code to the program which executed it.

What is difference between void main and int main?

The void main() indicates that the main() function will not return any value, but the int main() indicates that the main() can return integer type data. When our program is simple, and it is not going to terminate before reaching the last line of the code, or the code is error free, then we can use the void main().

Why do we return 0 in C?

These status codes are just used as a convention for a long time in C language because the language does not support the objects and classes, and exceptions. return 0: A return 0 means that the program will execute successfully and did what it was intended to do.

What should main return C?

What should main() return in C and C++? The return value for main is used to indicate how the program exited. If the program execution was normal, a 0 return value is used. Abnormal termination(errors, invalid inputs, segmentation faults, etc.) is usually terminated by a non-zero return.

What is the purpose of int main void?

Int main(void) is used in C to restrict the function to take any arguments, if you dont put void in those brackets, the function will take ANY number of arguments you supply at call.

Why is Main an int?

The short answer, is because the C++ standard requires main() to return int . As you probably know, the return value from the main() function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished.

What is int main void?

int main() indicates that the main function can be called with any number of parameters or without any parameter. On the other hand, int main(void) indicates that the main function will be called without any parameter #include int main() { static int i = 5; if (–i){ printf(“%d “, i); main(10); } }

Why void main is wrong in C?

It’s non-standard. The int returned by main() is a way for a program to return a value to the system that invokes it. On systems that doesn’t provide such a facility the return value is ignored, but that doesn’t make void main() legal. Even if your compiler accepts void main() avoid it in any case. It’s incorrect.

What’s the difference between int main and void main?

A conforming implementation may provide more versions of main (), but they must all have return type int. The int returned by main () is a way for a program to return a value to “the system” that invokes it. On systems that doesn’t provide such a facility the return value is ignored, but that doesn’t make “void main ()” legal C++ or legal C.

Is it legal to write void main ( ) in C?

*/ } A conforming implementation may provide more versions of main (), but they must all have return type int. The int returned by main () is a way for a program to return a value to “the system” that invokes it. On systems that doesn’t provide such a facility the return value is ignored, but that doesn’t make “void main ()” legal C++ or legal C.

Why do I get an error with void main ( )?

However, with Xcode I’m getting an error that says, “error: ‘::main’ must return ‘int’”. Can anyone toss me some insight into why I’m getting this error, and how I may be able to correct it so that the compiler accepts main() as ‘void’?

What does’main’must return’int’in C + +?

The main function of a C++ program must return an int. This means that unlike some other programming languages, you cannot have the following: void main() {} void main(args) {} long main() {}. If you do this, you have not written a C++ program, and all respectable, ISO standard-compliant C++ compilers will reject the above code.

Solution 1

Try doing this:

int main(int argc, char **argv)
{
    // Code goes here

    return 0;
}

The return 0; returns a 0 to the operating system which means that the program executed successfully.

Solution 2

C++ requires main() to be of type int.

Solution 3

Function is declared as int main(..);, so change your void return value to int, and return 0 at the end of the main function.

Related videos on Youtube

Gumball | Darwin's Potato Diet | The Potato | Cartoon Network

05 : 16

Gumball | Darwin’s Potato Diet | The Potato | Cartoon Network

The Amazing World of Gumball

Day 1 Syndicate Crown — CrossFit Semifinal

07 : 17 : 42

Day 1 Syndicate Crown — CrossFit Semifinal

Zara Larsson - Ain't My Fault (Official Video)

03 : 44

Zara Larsson — Ain’t My Fault (Official Video)

Westlife - If I Let You Go (Official Video)

03 : 39

Westlife — If I Let You Go (Official Video)

Confronting Ray Dalio on America's Next Big Problem | Ep. 613

01 : 18 : 35

Confronting Ray Dalio on America’s Next Big Problem | Ep. 613

THE JORDAN HARBINGER SHOW

What is the difference between int main( ) and void main( ) in c programming ?

02 : 54

What is the difference between int main( ) and void main( ) in c programming ?

Why Humans Sacrifice

01 : 02 : 59

How to stay calm when you know you'll be stressed | Daniel Levitin

12 : 21

How to stay calm when you know you’ll be stressed | Daniel Levitin

Branding Etiquette - Do's, Don't's, and How to Be Good Help at a Branding

34 : 54

Branding Etiquette — Do’s, Don’t’s, and How to Be Good Help at a Branding

USB Error Code 39 In Windows 10 [Tutorial]

01 : 15

USB Error Code 39 In Windows 10 [Tutorial]

Comments

  • This my main function:

    void main(int argc, char **argv)
    {
        if (argc >= 4)
        {
            ProcessScheduler *processScheduler;
            std::cout <<
                "Running algorithm: " << argv[2] <<
                "nWith a CSP of: " << argv[3] <<
                "nFilename: " << argv[1] <<
                std::endl << std::endl;
    
            if (argc == 4)
            {
                processScheduler = new ProcessScheduler(
                    argv[2],
                    atoi(argv[3])
                );
            }
            else
            {
                processScheduler = new ProcessScheduler(
                    argv[2],
                    atoi(argv[3]),
                    atoi(argv[4]),
                    atoi(argv[5])
                );
            }
            processScheduler -> LoadFile(argv[1]);
            processScheduler -> RunProcesses();
    
            GanntChart ganntChart(*processScheduler);
            ganntChart.DisplayChart();
            ganntChart.DisplayTable();
            ganntChart.DisplaySummary();
    
            system("pause");
    
            delete processScheduler;
        }
        else
        {
            PrintUsage();
        }
    }
    

    The error I get when I compile is this:

    Application.cpp:41:32: error: ‘::main’ must return ‘int’

    It’s a void function how can I return int and how do I fix it?

    • Change the signature to int.

    • What’s unclear about that error message for you?

  • The return 0; is implied in C++, and unnecessary.

  • Yes I agree. It is there for convention and is good practice to include so there’s no ambiguity.

  • Thanks, I wanted to have void main and return nothing but I guess it has to be int. after changing void to int that did solve the error

  • Thanks, I didn’t know about that. I thought you could have void main

  • @Michael this is not the solution.

  • @Nick Pavini, do you have any documentation? please share with us.

  • @roottraveller can you provide some insight as to why it isn’t?

Recents

Related

Понравилась статья? Поделить с друзьями:
  • Ошибка lua51 dll
  • Ошибка main bios checksum error
  • Ошибка lua интерфейс
  • Ошибка main beam bulb faulty
  • Ошибка lua wow circle