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
3,0647 gold badges37 silver badges82 bronze badges
asked Nov 2, 2016 at 14:05
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
MichaelMichael
3,0647 gold badges37 silver badges82 bronze badges
5
C++ requires main()
to be of type int
.
answered Nov 2, 2016 at 14:18
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
renonszrenonsz
5711 gold badge4 silver badges17 bronze badges
Romanusgho 0 / 0 / 0 Регистрация: 19.09.2019 Сообщений: 10 |
||||
1 |
||||
01.10.2019, 22:10. Показов 14182. Ответов 10 Метки нет (Все метки)
должно быть всё верно но вылазит ошибочка,кто знает в чем трабл
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 |
|||||||
double main()
int v, x, y,z,k;
1 |
3571 / 2239 / 406 Регистрация: 09.09.2017 Сообщений: 9,377 |
|
02.10.2019, 10:01 |
4 |
должно быть всё верно но вылазит ошибочка Если бы вы попытались скомпилировать свой код и посмотрели что же именно за «ошибочка», сами бы и исправили: Код $ g++ main.c -Wall -Wextra -Wpedantic main.c:6:13: error: ‘::main’ must return ‘int’ double main() функция main по стандарту должна быть объявлена как Код 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 |
но допускается и вариант int main( void ). Исправляем. Ну-ну, давайте будем грамотными и таки говорить о С++ в разделе о С++ и не подкладывать свинью начинающим, ато еще так и писать начнут да людей путать.
0 |
285 / 176 / 21 Регистрация: 16.02.2018 Сообщений: 666 |
|
02.10.2019, 12:32 |
6 |
в Си он играет свою роль (тк там без него будет елипсис) 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 |
void здесь абсолютно не нужен в Си он играет свою роль (тк там без него будет елипсис), в С++ свою. В C++ этот void не обязателен. Да, собственно говоря, в Си он тоже не ахти какая ошибка: без него функцию main() можно вызывать с произвольными аргументами, но в коде они использоваться все равно не будут, а за целостностью стека следит вызывающая сторона, которая сама за собой приберет.
0 |
Azazel-San Mental handicap 1245 / 623 / 171 Регистрация: 24.11.2015 Сообщений: 2,429 |
||||||||
02.10.2019, 13:26 |
8 |
|||||||
N1570 6.7.6.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. Отсюда вывод, что такое:
вполне легально.
знач там не елипсис, а просто аргументы/кол-во аргументов не определено? Добавлено через 8 минут
без него функцию main() можно вызывать с произвольными аргументами, но в коде они использоваться все равно не будут Что это значит? Как оказалось все не так просто и это может быть UB?
If the expression […] выделил основное.
UB.
0 |
285 / 176 / 21 Регистрация: 16.02.2018 Сообщений: 666 |
|
02.10.2019, 13:37 |
9 |
Хм, знач там не елипсис, а просто аргументы/кол-во аргументов не определено? Да. 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 |
Да. Буду знать, спасибо.
0 |
3571 / 2239 / 406 Регистрация: 09.09.2017 Сообщений: 9,377 |
|
02.10.2019, 14:22 |
11 |
Получается, если смотреть мой пост выше, такая запись: Насколько я понимаю, вся неопределенность что в хедере можно объявить
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
|
|
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
05 : 16
Gumball | Darwin’s Potato Diet | The Potato | Cartoon Network
The Amazing World of Gumball
07 : 17 : 42
Day 1 Syndicate Crown — CrossFit Semifinal
03 : 44
Zara Larsson — Ain’t My Fault (Official Video)
03 : 39
Westlife — If I Let You Go (Official Video)
01 : 18 : 35
Confronting Ray Dalio on America’s Next Big Problem | Ep. 613
THE JORDAN HARBINGER SHOW
02 : 54
What is the difference between int main( ) and void main( ) in c programming ?
01 : 02 : 59
12 : 21
How to stay calm when you know you’ll be stressed | Daniel Levitin
34 : 54
Branding Etiquette — Do’s, Don’t’s, and How to Be Good Help at a Branding
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?