Error 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,0647 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,0647 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

Romanusgho

0 / 0 / 0

Регистрация: 19.09.2019

Сообщений: 10

1

01.10.2019, 22:10. Показов 14182. Ответов 10

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

должно быть всё верно но вылазит ошибочка,кто знает в чем трабл

C++
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
#include <iostream>
#include <math.h>
 
using namespace std;
 
double main()
{
    int v, x, y,z,k;
    int min1=0.0;
    int max=0.0;
    int min2=0.0;
    
    cout << "input x:n> ";
        cin >> x;
    cout << "input y:n> ";
        cin >> y;
    if (x>0.0)
     min1=0.0;
    else
     min1=x;
    if (y>0.0)
     min2=0.0;
    else 
     min2=y;
     
    if (x>y)
    max=x;
    
    
    else
    max=y;
    
    z=pow(max,2.0);
    k=min1-min2; 
        
    v=k/z;
 
    cout << "v=" << v <<endl;
    
    return 0;
}



0



7427 / 5021 / 2891

Регистрация: 18.12.2017

Сообщений: 15,694

02.10.2019, 00:40

2

Romanusgho, напишите условие задачи



0



long399

Модератор

2547 / 1644 / 895

Регистрация: 16.10.2013

Сообщений: 4,865

Записей в блоге: 13

02.10.2019, 05:28

3

Цитата
Сообщение от Romanusgho
Посмотреть сообщение

double main()

C++
1
int main()

Цитата
Сообщение от Romanusgho
Посмотреть сообщение

int v, x, y,z,k;
int min1=0.0;
int max=0.0;
int min2=0.0;

C++
1
2
3
4
double v, x, y,z,k;
double min1=0.0;
double max=0.0;
double min2=0.0;



1



3571 / 2239 / 406

Регистрация: 09.09.2017

Сообщений: 9,377

02.10.2019, 10:01

4

Цитата
Сообщение от Romanusgho
Посмотреть сообщение

должно быть всё верно но вылазит ошибочка

Если бы вы попытались скомпилировать свой код и посмотрели что же именно за «ошибочка», сами бы и исправили:

Код

$ g++ main.c -Wall -Wextra -Wpedantic
main.c:6:13: error: ‘::main’ must return ‘int’
 double main()

функция main по стандарту должна быть объявлена как int main( int argc, char *argv[] ), но допускается и вариант int main( void ). Исправляем.

Код

 g++ main.c -Wall -Wextra -Wpedantic
$ ./a.out 
input x:
> 1
input y:
> 2
v=0

Как видите, ошибка больше не возникает. А что при присвоении дробных чисел целочисленным преременным идет округление вниз, long399 уже написал.



1



Mental handicap

1245 / 623 / 171

Регистрация: 24.11.2015

Сообщений: 2,429

02.10.2019, 10:54

5

Цитата
Сообщение от COKPOWEHEU
Посмотреть сообщение

но допускается и вариант int main( void ). Исправляем.

Ну-ну, давайте будем грамотными и таки говорить о С++ в разделе о С++ и не подкладывать свинью начинающим, ато еще так и писать начнут да людей путать.
void здесь абсолютно не нужен в Си он играет свою роль (тк там без него будет елипсис), в С++ свою.
Все таки это разные языки.



0



285 / 176 / 21

Регистрация: 16.02.2018

Сообщений: 666

02.10.2019, 12:32

6

Цитата
Сообщение от Azazel-San
Посмотреть сообщение

в Си он играет свою роль (тк там без него будет елипсис)

N1570 6.7.6.3/14

An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters.



1



3571 / 2239 / 406

Регистрация: 09.09.2017

Сообщений: 9,377

02.10.2019, 12:48

7

Цитата
Сообщение от Azazel-San
Посмотреть сообщение

void здесь абсолютно не нужен в Си он играет свою роль (тк там без него будет елипсис), в С++ свою.

В C++ этот void не обязателен. Да, собственно говоря, в Си он тоже не ахти какая ошибка: без него функцию main() можно вызывать с произвольными аргументами, но в коде они использоваться все равно не будут, а за целостностью стека следит вызывающая сторона, которая сама за собой приберет.
Я сталкивался с более интересной особенностью: библиотека SDL требует объявления main строго как int main( int argc, char **argv ) и никак иначе. В противном случае ошибка линковки.



0



Azazel-San

Mental handicap

1245 / 623 / 171

Регистрация: 24.11.2015

Сообщений: 2,429

02.10.2019, 13:26

8

Цитата
Сообщение от rat0r
Посмотреть сообщение

N1570 6.7.6.3/14

Спасибо за поправку.
Получается, в Си все ок? Все время думал там елипсис будет (я в Си не шарю).
Да и везде говорят (на SO), что тогда туда можно что угодно засунуть..
Хм, знач там не елипсис, а просто аргументы/кол-во аргументов не определено?
Открыл стандарт Си (впервые), там есть еще и продолжение:

Цитата
Сообщение от N1256 6.7.5.3/14

An identifier list declares only the identifiers of the parameters of the function. An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters. The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.

Отсюда вывод, что такое:

C
1
2
3
4
void foo(); // declaration
...
void foo(int a, int b) // definition
{ }

вполне легально.
То мои мысли верны?

Цитата
Сообщение от Azazel-San

знач там не елипсис, а просто аргументы/кол-во аргументов не определено?

Добавлено через 8 минут

Цитата
Сообщение от COKPOWEHEU
Посмотреть сообщение

без него функцию main() можно вызывать с произвольными аргументами, но в коде они использоваться все равно не будут

Что это значит? Как оказалось все не так просто и это может быть UB?
Открыл стандарт Си (второй раз):

Цитата
Сообщение от N1256 6.5.2.2/6

If the expression […]
If the function is defined with a type that does not include a prototype, and the types of
the arguments after promotion are not compatible with those of the parameters after
promotion, the behavior is undefined
[…]

выделил основное.
Получается, если смотреть мой пост выше, такая запись:

C
1
2
3
4
void foo() {}
...
char* str;
foo(str); // <- вызов ф-и

UB.



0



285 / 176 / 21

Регистрация: 16.02.2018

Сообщений: 666

02.10.2019, 13:37

9

Цитата
Сообщение от Azazel-San
Посмотреть сообщение

Хм, знач там не елипсис, а просто аргументы/кол-во аргументов не определено?

Да. Any number of arguments ≠ variable number of arguments.



1



Mental handicap

1245 / 623 / 171

Регистрация: 24.11.2015

Сообщений: 2,429

02.10.2019, 13:40

10

Цитата
Сообщение от rat0r
Посмотреть сообщение

Да.

Буду знать, спасибо.



0



3571 / 2239 / 406

Регистрация: 09.09.2017

Сообщений: 9,377

02.10.2019, 14:22

11

Цитата
Сообщение от Azazel-San
Посмотреть сообщение

Получается, если смотреть мой пост выше, такая запись:
UB.

Насколько я понимаю, вся неопределенность что в хедере можно объявить int func(); потом в реализации записать int func(int x){...} а вызывать как func("str");
Но если реализация свой аргумент не использует — какая ей разница что напихали в стек / регистры.



0



  • 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)

  • Ссылка

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

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

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти телефон список сайтов
  • Как найти грамматическую основу сложного предложения
  • Client not responding dayz как исправить
  • Как найти количество кубиков в кубе
  • Как найди максимальную прибыль

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии