Меню

Void main void ошибка

qubaidolla

0 / 0 / 0

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

Сообщений: 1

1

04.01.2020, 08:08. Показов 6429. Ответов 2

Метки c++ (Все метки)


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
#include <iostream>
using namespace std;
void main /* Проблема в нем () */
{
    setlocale (LC_ALL, "rus");
 
    int a;
    cin >> a;
 
    switch (a)
 
    {
    case 1:
        cout << "Вы ввели 1";
        break;
    
    case 2:
        cout << "Вы ввели 2";
        break;
    
    default:
        cout << "Я не понимаю";
        break;  
    }
 
 
cin.get();
return 0;
}

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



0



5666 / 3112 / 1299

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

Сообщений: 7,806

04.01.2020, 08:09

2

int main()



1



653 / 466 / 183

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

Сообщений: 1,987

04.01.2020, 17:14

3



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

04.01.2020, 17:14

3

I have typed in the following code in Ubuntu using Emacs and compiled using the command line

#include <stdio.h>

int main(void)
{
  printf("Hello World!nn");
  return 0;
}

Having the void in the main function argument returns the following warning

helloworld.c: In function ‘main’:
helloworld.c:6:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

When I removed the «void» within the parenthesis the program compiled without any errors. What is incorrect in have main(void) in this program?

Compilation command is
gcc -Wall -ggdb helloworld.c -o hello

Edit:
This is the screenshot which I would like to share
enter image description here

asked Dec 23, 2015 at 19:48

Prasanna's user avatar

PrasannaPrasanna

3032 silver badges16 bronze badges

6

The error doesn’t have anything to do with the void in the signature of main() int main(void) is correct and is the way to define main() when you don’t need to handle command line arguments.

The error means that you defined int main(void) and you did not return a value from the function. Like this

#include <stdio.h>

int main(void) 
{
    printf("Hello World!n");    
}

This warning was removed for main() in newer versions of gcc because main() implicitly returns 0 when the program exits unless you indicate otherwise with exit() or an explict return from main().

Normal functions still trigger this warning and it helps in prevention of undefined behavior due to not returning from a function and trying to capture the return value.

answered Dec 23, 2015 at 19:51

Iharob Al Asimi's user avatar

Iharob Al AsimiIharob Al Asimi

52.4k6 gold badges59 silver badges96 bronze badges

2

The only way that warning could be for main() function is if you don’t have a return statement and you are compiling in C89/C90 mode.

Since C99, a return statement at the end of main() is not required and it’ll be assumed to return 0; if control returns from main()‘s end. So compile in c99 or C11 mode:

gcc -Wall -ggdb -std=c11 helloworld.c -o hello

which won’t trigger that warning. Or make sure you have return statement if you are compiling in c89/C90. Until recently (at least upto gcc 4.9), the default mode in gcc is gnu90. So you would get that warning withot a return statement if you don’t passstd=.

I presume you don’t actually have return 0; in your real code that produces this warning as it wouldn’t matter in what mode of C you are compiling it if you had an explicit return statement.

answered Dec 23, 2015 at 20:06

P.P's user avatar

P.PP.P

116k20 gold badges170 silver badges231 bronze badges

9

I have typed in the following code in Ubuntu using Emacs and compiled using the command line

#include <stdio.h>

int main(void)
{
  printf("Hello World!nn");
  return 0;
}

Having the void in the main function argument returns the following warning

helloworld.c: In function ‘main’:
helloworld.c:6:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

When I removed the «void» within the parenthesis the program compiled without any errors. What is incorrect in have main(void) in this program?

Compilation command is
gcc -Wall -ggdb helloworld.c -o hello

Edit:
This is the screenshot which I would like to share
enter image description here

asked Dec 23, 2015 at 19:48

Prasanna's user avatar

PrasannaPrasanna

3032 silver badges16 bronze badges

6

The error doesn’t have anything to do with the void in the signature of main() int main(void) is correct and is the way to define main() when you don’t need to handle command line arguments.

The error means that you defined int main(void) and you did not return a value from the function. Like this

#include <stdio.h>

int main(void) 
{
    printf("Hello World!n");    
}

This warning was removed for main() in newer versions of gcc because main() implicitly returns 0 when the program exits unless you indicate otherwise with exit() or an explict return from main().

Normal functions still trigger this warning and it helps in prevention of undefined behavior due to not returning from a function and trying to capture the return value.

answered Dec 23, 2015 at 19:51

Iharob Al Asimi's user avatar

Iharob Al AsimiIharob Al Asimi

52.4k6 gold badges59 silver badges96 bronze badges

2

The only way that warning could be for main() function is if you don’t have a return statement and you are compiling in C89/C90 mode.

Since C99, a return statement at the end of main() is not required and it’ll be assumed to return 0; if control returns from main()‘s end. So compile in c99 or C11 mode:

gcc -Wall -ggdb -std=c11 helloworld.c -o hello

which won’t trigger that warning. Or make sure you have return statement if you are compiling in c89/C90. Until recently (at least upto gcc 4.9), the default mode in gcc is gnu90. So you would get that warning withot a return statement if you don’t passstd=.

I presume you don’t actually have return 0; in your real code that produces this warning as it wouldn’t matter in what mode of C you are compiling it if you had an explicit return statement.

answered Dec 23, 2015 at 20:06

P.P's user avatar

P.PP.P

116k20 gold badges170 silver badges231 bronze badges

9

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 badges36 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 badges36 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

  • Forum
  • Beginners
  • void main problem

void main problem

i am trying to use this given tutorial and main needs to be void for future tutorials, but every time i compile it as void, it gives an error saying main must return an int. Although on the tutorial it worked.
I know math.h and string do not need to be there, but it is for future purposes.

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
#include <iostream>
#include <math.h>
#include <string>
using namespace std;


void main()
{
    int people;
    float bill, tip, totaltip, total;

    cout << "How much is the bill? ";
    cin >> bill;
    cout <<"How many people will be splitting the bill? ";
    cin >> people;
    cout << "What is the percetage of the tip? ";
    cin >> tip;

    totaltip = bill *(tip/100.);
    total = (totaltip + bill) /people;

    cout << "The total tip at %" << tip << " is $" << totaltip << '.' << endl;
    cout << "Each person will pay $" << total << '.' << endl;
   
}

Last edited on

metulburr wrote:
main must return an int

Last edited on

though it works on other peoples tutorials?

I would probably find a different tutorial…

The standard says main must return an int, but apparently some compilers will let you get away with void. I just tested with msvc 2010, and it will compile

without warning.

yeah dude, main() most definitely returns an int. Consider this simple boilerplate code:
int main(int nArgs, char* pszArgs)

its kinda just what i was told to impliment in all my main methods and i would be safe

Topic archived. No new replies allowed.

Функция main() возвращает тип int. Если вы уже это знаете, то и не читайте.

Если вы присвоите функции main() тип возврата, отличный от int, то в компиляторах, предшествующих компиляторам С99, вы получите неопределенное поведение своей программы. В компиляторах С99 вы получите неспецифицированное поведение, если так говорит реализация версии, или неопределенное поведение — если она этого не делает. Доверяете ли вы своей программе в этом отношении?

Многие просто не верят мне, когда я говорю им это (точно так же, как не верил я, когда впервые узнал об этом). Частично это связано с тем, что несколько широко известных учебников по С и, по крайней мере, по одной авторитетной программе-компилятору используют void main() с тревожной регулярностью. Ниже приведена формулировка стандарта С99 (который фактически чуть более снисходителен, чем стандарт С89, который вам, возможно, более знаком):

5.1.2.2.1. Запуск программы. Функция, вызывающая запуск программы, называется main (главная). Реализация не объявляет прототип для этой функции. Он должен быть определен путем возврата целого типа int без параметров:

int main (void) {  /*  …  */  }

либо с двумя параметрами (здесь они называются argc и argv, хотя можно использовать любые имена в том порядке, как они размещены в функции, в которой объявлены):

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

либо некоторым другим определенным реализацией способом».

5.1.2.2.3. Завершение программы. Если возвращаемый главной функцией тип является типом, совместимым с int, то возврат в главную функцию эквивалентен вызову функции выхода со значением, возвращенным главной функцией в качестве ее аргумента; при достижении скобки }, которая завершает главную функцию, возвращается значение 0. Если возвращаемый тип несовместим с типом int, состояние завершения, возвращаемое в хост-среду, является неспецифицированным».

В данном контексте «неспецифицированный» означает, что стандарт не требует какого-либо специфического поведения от компилятора, который волен возвратить в хост-среду (обычно это операционная система) любое состояние, какое ему нравится, и это применяется, только если документами реализации установлено, что она поддерживает возвращаемые из main () типы, отличные от int. Если у вас пустая (void) главная функция main () и вы пишете код для ядерного реактора или военного самолета, вы, возможно, почувствуете легкую нерешительность, и я не виню вас. Кроме того, определение main () для возврата типа void (пустой) не является синтаксической ошибкой или нарушением ограничения, так что компилятор не обязательно должен выдавать какое-либо диагностическое сообщение.

Давайте посмотрим на это несколько под иным углом. Рассмотрим четвертый аргумент функции сортировки qsort. Он специфицирован как указатель на некую функцию сравнения, принимающую в качестве аргументов две константы типа const void * и возвращающую тип int. Функция qsort вызывает эту функцию сравнения и использует возвращенное ею значение для установления взаимоотношений между двумя объектами в массиве, который подлежит сортировке. Так вот, что случится, если вы напишете функцию сравнения, подобную этой?

void CompInts (const void *pl,  const void *p2)
{
    const int  *nl  = pi;
    const int  *n2  = p2;
    int diff;
    if(*nl > *n2)
        diff = 1;
    else if(*nl == *n2)
        diff = 0;
    else
        diff = -1;
}

Слов нет, верно? У функции qsort нет способа получить информацию, в которой она нуждается. Вы не можете специфицировать прототип функций сравнения — вам потребуется отбросить правила обращения к функции qsort, если вы хотите заставить эту функцию делать то, чего от нее ожидаете.

Хорошо, вернемся к функции main (). Здесь точно такая же ситуация. Вы не ответственны за определение интерфейса main(). Для этого есть вызывающая функция. Кто вызывает main()? Это не вы (хотя фактически вы можете, если захотите, вызвать main(), точно так же как вы можете при желании вызвать свою функцию сравнения из qsort). Но первичным «заказчиком» функции main() является код запуска. Как же код запуска определит, успешно ли завершилась программа, если вы не сообщите ему об этом? Этот вызов «сидит» где-то глубоко во внутренностях системы (здесь я немного упростил его):

int returnstatus;
returnstatus = main  (argc,  argv);

Если вы «опустошите» функцию main (), появится несколько интересных возможностей:

  • Программа может работать в точности так, как вы ожидаете.
  • returnstatus может попасть в ловушку и вызвать аварийный отказ программы (либо всего компьютера).
  • Код запуска может отправить поддельный код возврата операционной системе, которая затем решит перемотать назад транзакции базы данных, поскольку программа не возвратила ожидаемого значения.
  • А это хуже всего — код запуска может снаружи достигнуть вашего носа и начать извлекать из него демонов. (Демон (Demon) — процедура, запускаемая автоматически при выполнении некоторых условий и характеризуемая непредсказуемостью поведения. — Прим. науч. ред.).

Функция main () возвращает тип int. Существует только три переносимых на другие платформы значения, которые вы можете вернуть из main ():

  • 0
  • EXITSDCCESS
  • EXIT_FAILURE

Два последние определены в <stdlib.h>, и их фактические значения варьируются в зависимости от конкретной системы. (Другими словами, не следует отыскивать эти значения в библиотеке <stdlib.h> и переносить их в свою программу.)

Если вы вернули 0, код запуска сообщит операционной системе или другой хост-среде, что ваша программа выполнилась успешно, переведя 0 при необходимости в некоторое другое значение.

Количество аргументов функции main ()

Фактически функцию можно определить путем определения реализации. Следовательно, такое определение main, как

ИЛИ

int main  (int argc,  char **argv,  char **env)

не обязательно запрещено, но вы должны знать, что компилятор обязан поддерживать любое из этих двух определений. Они разрешены только для компиляторов, которые документируют эти альтернативные формы и которые конечно же не включают всех компиляторов.

Ниже приведены переносимые определения функции main ():

  • int main (void)
  • int main (int argc, char **argv)
  • int main (int argc, char **argv [ ] )
  • Любое определение, в точности эквивалентное любому из трех предыдущих

Таким образом, вы можете использовать различные имена переменных в качестве argc и argv, а также можете использовать FOO, если определению предшествует typedef int FOO, и т.д. Но чтобы возвращаемое значение было переносимым, из main вы должны возвращать тип int, а также задавать либо ни одного аргумента, либо два специфицированных стандартом аргумента. Если есть необходимость получить доступ к среде переносимым способом, можете, конечно, использовать функцию getenv ().

© Ричард Хэзфилд, «Искусство программирования на C», 2001 год.

Looks like no one’s replied in a while. To start the conversation again, simply

ask a new question.

Hey there. I’ve just started taking a object-oriented C++ course online — it’s been a few years since I’ve programmed C++, although I’ve programmed C more recently. Anyways, they expect me to use Visual Studio as my compiler, but I’m not budging — Xcode is where I like to write my code, and I don’t feel like reinstalling Parallels. The problem is, the code I’m supposed to use for one of the exercises defines main() using ‘void’ instead of ‘int’. In my experience programming C (and C++ if I’m not mistaking), this has never been a problem. 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’? I’ve checked the project settings under «GCC 4.0 — Language», but I didn’t find anything I could recognize as relevant, other than «C Language Dialect» being set to C99, and I don’t think that’s the issue.

Any help is appreciated — thanks.

MacBook,

Mac OS X (10.5.8)

Posted on Sep 5, 2010 4:21 AM

Tron55555 wrote:

So I guess there’s no easy way around that then?

The easy answer is to use int. Like a number of things in the Windows world, «void main()» is flat-out syntactically invalid. The Microsoft Foundation Class library will not compile with a standards-compliant C++ compiler — because it isn’t valid C++. Microsoft’s compilers have switches to enable standards compliance, but you should never use them. GCC has switches to enable it to compile MFC, but no one ever uses them.

Apple gets a lot of press with the iPad and iPhone, but the reality is that Macs are still a distant minority in any corporate/educational environment. University professors, including those in Computer Science, are known for living 20 years in the past.

You are going to have to do what every Mac user in a computer science class has always done, write your code on your Mac because you love the Mac, then port it to Windows or whatever else. You are going to need Parallels for this course. The end result is that your code will be better than anyone else’s in the class. You have to write code good enough to satisfy two compilers and you will be a better programmer for it.

Posted on Sep 6, 2010 6:24 AM

error with ‘void main()’ in C++ tool

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

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

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Voicemod ошибка настройки аудиоустройства
  • Voice install could not be verified ошибка