Ошибка 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

Romanusgho

0 / 0 / 0

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

Сообщений: 10

1

01.10.2019, 22:10. Показов 14294. Ответов 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

Модератор

2548 / 1647 / 897

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

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

Записей в блоге: 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



3581 / 2250 / 407

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

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

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



3581 / 2250 / 407

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

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

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



3581 / 2250 / 407

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

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

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.

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.

>>‘::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)

  • Ссылка

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

Понравилась статья? Поделить с друзьями:
  • Ошибка mandatory directory has not been created
  • Ошибка main method not found
  • Ошибка man tga edc 03779 10
  • Ошибка main inspection performed on time w211
  • Ошибка man tga edc 03063 01