Ошибка main должен возвращать int

47 / 47 / 15

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

Сообщений: 584

1

09.03.2011, 18:49. Показов 4019. Ответов 3


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

ошибка: `main» должен вернуть `int» и т.д. перепробовал много вариантов у меня DEV C++ понятно что с тех пор как написали c++ для чайников и много другой литературы изменился стандарт вместо iostream.h iostream и т.д. подскажите чего делать,или название адекватной литературы или как с этим бороться.



0



ValeryS

Модератор

Эксперт по электронике

8812 / 6594 / 896

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

Сообщений: 23,195

09.03.2011, 18:56

2

C
1
2
3
4
5
int main()
{
..............................
return 0;
}

или я не понял вопроса?



0



1080 / 1006 / 106

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

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

09.03.2011, 18:58

3



0



Valerko

19 / 19 / 2

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

Сообщений: 164

09.03.2011, 22:04

4

C++
1
2
3
4
5
6
7
8
include <...>
 
int main()
{
/* тело функции*/
 
return 0;
}



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

09.03.2011, 22:04

Помогаю со студенческими работами здесь

Ошибка компилирования «error: ‘::main’ must return ‘int’»
должно быть всё верно но вылазит ошибочка,кто знает в чем трабл
#include &lt;iostream&gt;
#include…

Ошибка при сборке многофайлового проекта: «невозможно преобразовать «int» в «const golf»
Сделал многофайловую программу программу, вот она:
//golf.h
#include &lt;iostream&gt;
#ifndef golg_h_…

Ошибка: «невозможно преобразовать аргумент 1 из «int [3][3]» в «int **»»
Приветствую, сделал задание, но выдает вот такую ошибку &quot;int sum(int **,int)&quot;: невозможно…

Ошибка «error C2446: :: нет преобразования «int» в «char *»
Ошибка: &quot;error C2446: :: нет преобразования &quot;int&quot; в &quot;char *&quot;

Когда нажимаю двойным кликом на…

В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно»
В зависимости от времени года &quot;весна&quot;, &quot;лето&quot;, &quot;осень&quot;, &quot;зима&quot; определить погоду &quot;тепло&quot;,…

Ошибка: «Отсутствует оператор «>>», соотвествующий этим операндам. Типы операндов: std::ifsteam>>int*»
#include&lt;fstream&gt;
#include&lt;iostream&gt;
#include &lt;string&gt;
using namespace std;
int main()
{…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

4

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 badges83 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 badges83 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 badges15 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

I am currently using Putty virtual machine (UNIX) for my class, and we are doing a short C++ assignment. The assignment is to:
«Create a C++ program that tests to see if the file accounts exists and prints a message to say whether the file exists»

This is what I have, but when I try to compile the code, I get this error:
error: ‘::main’ must return ‘int’

#include<iostream>
#include<fstream>

using namespace std;
inline bool exists_test1 (const std::string& name) {

if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}

void main()
{
string s;
cout<<"Enter filename";
cin>>s;
bool ans =exists_test1(s);
if(ans)
{
cout<<"File Exist"<<endl;
}
else
{
cout<<"File Does not Exist";
}
}

asked Dec 5, 2016 at 3:47

Migro96's user avatar

Migro96Migro96

591 gold badge1 silver badge8 bronze badges

2

The return type of main is int. This is defined by the C++ standard. In my local copy of the C++11 draft it’s outlined in § 3.6.1 Main Function :

  1. An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

    int main() { /* ...  */ }
    

    and

    int main(int argc, char* argv[]) { /* ...  */ }
    

Therefore your program is ill-formed according to the standard, and you compiler is rightly reporting it as an error. Define your function instead as:

int main()
{
    // your code...

    return 0;
}

answered Dec 5, 2016 at 3:55

paddy's user avatar

paddypaddy

60.1k6 gold badges59 silver badges102 bronze badges

1

Перейти к контенту

47 / 47 / 15

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

Сообщений: 584

1

09.03.2011, 18:49. Показов 3802. Ответов 3


ошибка: `main» должен вернуть `int» и т.д. перепробовал много вариантов у меня DEV C++ понятно что с тех пор как написали c++ для чайников и много другой литературы изменился стандарт вместо iostream.h iostream и т.д. подскажите чего делать,или название адекватной литературы или как с этим бороться.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

ValeryS

Модератор

Эксперт по электронике

8756 / 6546 / 887

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

Сообщений: 22,962

09.03.2011, 18:56

2

C
1
2
3
4
5
int main()
{
..............................
return 0;
}

или я не понял вопроса?

0

1080 / 1006 / 106

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

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

09.03.2011, 18:58

3

0

Valerko

19 / 19 / 2

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

Сообщений: 164

09.03.2011, 22:04

4

C++
1
2
3
4
5
6
7
8
include <...>
 
int main()
{
/* тело функции*/
 
return 0;
}

0

IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

09.03.2011, 22:04

Помогаю со студенческими работами здесь

Ошибка компилирования «error: ‘::main’ must return ‘int’»
должно быть всё верно но вылазит ошибочка,кто знает в чем трабл
#include &lt;iostream&gt;
#include…

Ошибка при сборке многофайлового проекта: «невозможно преобразовать «int» в «const golf»
Сделал многофайловую программу программу, вот она:
//golf.h
#include &lt;iostream&gt;
#ifndef golg_h_…

Ошибка: «невозможно преобразовать аргумент 1 из «int [3][3]» в «int **»»
Приветствую, сделал задание, но выдает вот такую ошибку &quot;int sum(int **,int)&quot;: невозможно…

Ошибка «error C2446: :: нет преобразования «int» в «char *»
Ошибка: &quot;error C2446: :: нет преобразования &quot;int&quot; в &quot;char *&quot;

Когда нажимаю двойным кликом на…

В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно»
В зависимости от времени года &quot;весна&quot;, &quot;лето&quot;, &quot;осень&quot;, &quot;зима&quot; определить погоду &quot;тепло&quot;,…

Ошибка: «Отсутствует оператор «>>», соотвествующий этим операндам. Типы операндов: std::ifsteam>>int*»
#include&lt;fstream&gt;
#include&lt;iostream&gt;
#include &lt;string&gt;
using namespace std;
int main()
{…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

4

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,0547 gold badges37 silver badges78 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,0547 gold badges37 silver badges78 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

2923 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

5611 gold badge4 silver badges17 bronze badges

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

  • Ссылка

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

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

Это моя основная функция:

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();
    }
}

Ошибка, которую я получаю при компиляции, такова:

Application.cpp: 41: 32: error: ‘:: main’ должен возвращать ‘int’

Это функция void, как я могу вернуть int и как ее исправить?

  • 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 cpp 312
  • Ошибка main bios checksum error что делать
  • Ошибка main beam bulb faulty
  • Ошибка mail delivery system
  • Ошибка magic bullet looks sony vegas