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

I’ve been working through the «Programming: Principles and Practice using C++» book, and this example was meant to illustrate how data can be lost in type conversions. But when I tried to execute it, it keeps telling me ‘Main’ : must return a value. I tried using «return 0;» after the curly brace for the while loop, but then it gave errors around «Unresolved externals».

I’ve copied the code from the book to Visual Studio and everything else I’ve copied has worked as expected — would anyone be able to tell me how I could fix this please? I don’t know why it’s happening with this specific example or how to make it stop asking for a return value.

Sorry if this is dumb, I’m very inexperienced and I’ve tried googling for an answer, but suggested solutions like «return 0» don’t work :)!

#include "std_lib_facilities.h"

int main()
{
    double d = 0;

    while (cin >> d)
    {

        int i = d;
        char c = i;
        int i2 = c;
        cout << "d==" << d
        << " i==" << i
        << " i2==" << i2
        << " char(" << c << ")n";
    }
}

asked Jan 29, 2016 at 21:09

Dean's user avatar

9

I tried using «return 0;» after the curly brace for the while loop, but then it gave errors around «Unresolved externals».

That’s a separate, unrelated problem uncovered by fixing the first one. Add the return, then deal with the unresolved externals error.

answered Jan 29, 2016 at 21:12

John Kugelman's user avatar

John KugelmanJohn Kugelman

347k67 gold badges524 silver badges574 bronze badges

3

If that’s your whole program, you’re unresolved external is most likely iostream. You need to include that and use the correct namespace.

Consider the following code:

#include <iostream>

using namespace std;

int main() {
   cout << "Hello World!" << endl;
   return 0;
}

Better yet, forgo the using statement and use std::cout so that you don’t have to worry about namespace collision. See this question Why is “using namespace std;” considered bad practice?

#include <iostream>

int main() {
   std::cout << "Hello World!" << std::endl;
   return 0;
}

Community's user avatar

answered Jan 29, 2016 at 21:17

zero298's user avatar

zero298zero298

25.1k8 gold badges73 silver badges99 bronze badges

8

47 / 47 / 15

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

Сообщений: 584

1

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


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

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



0



ValeryS

Модератор

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

8811 / 6593 / 896

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

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

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

#include<iostream>
using namespace std;

int var = 1;

void global(void)
{
    cout << "Global var = " << var << endl;
    return;
}


}
void main(void)
{
    int var = 100;
    global();
    cout << "Main var = " << var << endl;
    cout << "Main var = " << ::var << endl;
    system("pause");
    return;
}

задан 7 сен 2019 в 18:40

Андрей's user avatar

6

1 ответ

Конечно, согласно стандарту — cм. раздел 6.8.3.1 стандарта (например, тут).

Its type shall have C++ language linkage and it shall have a declared return type of type int

ответ дан 7 сен 2019 в 18:50

Harry's user avatar

HarryHarry

215k15 золотых знаков117 серебряных знаков228 бронзовых знаков

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

Standard C — Hosted Environment

For a hosted environment (that’s the normal one), the C11 standard (ISO/IEC 9899:2011) says:

5.1.2.2.1 Program startup

The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:

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

or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):

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

or equivalent;10) or in some other implementation-defined manner.

If they are declared, the parameters to the main function shall obey the following
constraints:

  • The value of argc shall be nonnegative.
  • argv[argc] shall be a null pointer.
  • If the value of argc is greater than zero, the array members argv[0] through
    argv[argc-1] inclusive shall contain pointers to strings, which are given
    implementation-defined values by the host environment prior to program startup. The
    intent is to supply to the program information determined prior to program startup
    from elsewhere in the hosted environment. If the host environment is not capable of
    supplying strings with letters in both uppercase and lowercase, the implementation
    shall ensure that the strings are received in lowercase.
  • If the value of argc is greater than zero, the string pointed to by argv[0]
    represents the program name; argv[0][0] shall be the null character if the
    program name is not available from the host environment. If the value of argc is
    greater than one, the strings pointed to by argv[1] through argv[argc-1]
    represent the program parameters.
  • The parameters argc and argv and the strings pointed to by the argv array shall
    be modifiable by the program, and retain their last-stored values between program
    startup and program termination.

10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as
char **argv, and so on.

Program termination in C99 or C11

The value returned from main() is transmitted to the ‘environment’ in an implementation-defined way.

5.1.2.2.3 Program termination

1 If the return type of the main function is a type compatible with int, a return from the
initial call to the main function is equivalent to calling the exit function with the value
returned by the main function as its argument;11) reaching the } that terminates the
main function returns a value of 0. If the return type is not compatible with int, the
termination status returned to the host environment is unspecified.

11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in main
will have ended in the former case, even where they would not have in the latter.

Note that 0 is mandated as ‘success’. You can use EXIT_FAILURE and EXIT_SUCCESS from <stdlib.h> if you prefer, but 0 is well established, and so is 1. See also Exit codes greater than 255 — possible?.

In C89 (and hence in Microsoft C), there is no statement about what happens if the main() function returns but does not specify a return value; it therefore leads to undefined behaviour.

7.22.4.4 The exit function

¶5 Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Standard C++ — Hosted Environment

The C++11 standard (ISO/IEC 14882:2011) says:

3.6.1 Main function [basic.start.main]

¶1 A program shall contain a global function called main, which is the designated start of the program. […]

¶2 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[]) { /* ... */ }

In the latter form argc shall be the number of arguments passed to the program from the environment
in which the program is run. If argc is nonzero these arguments shall be supplied in argv[0]
through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (NTMBSs) (17.5.2.1.4.2) and argv[0] shall be the pointer to the initial character of a NTMBS that represents the
name used to invoke the program or "". The value of argc shall be non-negative. The value of argv[argc]
shall be 0. [Note: It is recommended that any further (optional) parameters be added after argv. —end
note]

¶3 The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. […]

¶5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic
storage duration) and calling std::exit with the return value as the argument. If control reaches the end
of main without encountering a return statement, the effect is that of executing

return 0;

The C++ standard explicitly says «It [the main function] shall have a return type of type int, but otherwise its type is implementation defined», and requires the same two signatures as the C standard to be supported as options. So a ‘void main()’ is directly not allowed by the C++ standard, though there’s nothing it can do to stop a non-standard implementation allowing alternatives. Note that C++ forbids the user from calling main (but the C standard does not).

There’s a paragraph of §18.5 Start and termination in the C++11 standard that is identical to the paragraph from §7.22.4.4 The exit function in the C11 standard (quoted above), apart from a footnote (which simply documents that EXIT_SUCCESS and EXIT_FAILURE are defined in <cstdlib>).

Standard C — Common Extension

Classically, Unix systems support a third variant:

int main(int argc, char **argv, char **envp) { ... }

The third argument is a null-terminated list of pointers to strings, each of which is an environment variable which has a name, an equals sign, and a value (possibly empty). If you do not use this, you can still get at the environment via ‘extern char **environ;‘. This global variable is unique among those in POSIX in that it does not have a header that declares it.

This is recognized by the C standard as a common extension, documented in Annex J:

###J.5.1 Environment arguments

¶1 In a hosted environment, the main function receives a third argument, char *envp[],
that points to a null-terminated array of pointers to char, each of which points to a string
that provides information about the environment for this execution of the program (5.1.2.2.1).

Microsoft C

The Microsoft VS 2010 compiler is interesting. The web site says:

The declaration syntax for main is

 int main();

or, optionally,

int main(int argc, char *argv[], char *envp[]);

Alternatively, the main and wmain functions can be declared as returning void (no return value). If you declare main or wmain as returning void, you cannot return an exit code to the parent process or operating system by using a return statement. To return an exit code when main or wmain is declared as void, you must use the exit function.

It is not clear to me what happens (what exit code is returned to the parent or OS) when a program with void main() does exit — and the MS web site is silent too.

Interestingly, MS does not prescribe the two-argument version of main() that the C and C++ standards require. It only prescribes a three argument form where the third argument is char **envp, a pointer to a list of environment variables.

The Microsoft page also lists some other alternatives — wmain() which takes wide character strings, and some more.

The Microsoft Visual Studio 2005 version of this page does not list void main() as an alternative. The versions from Microsoft Visual Studio 2008 onwards do.

Standard C — Freestanding Environment

As noted early on, the requirements above apply to hosted environments. If you are working with a freestanding environment (which is the alternative to a hosted environment), then the standard has much less to say. For a freestanding environment, the function called at program startup need not be called main and there are no constraints on its return type. The standard says:

5.1.2 Execution environments

Two execution environments are defined: freestanding and hosted. In both cases,
program startup occurs when a designated C function is called by the execution
environment. All objects with static storage duration shall be initialized (set to their initial values) before program startup. The manner and timing of such initialization are otherwise unspecified. Program termination returns control to the execution environment.

5.1.2.1 Freestanding environment

In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. Any library facilities available to a freestanding program, other than the minimal set required by clause 4, are implementation-defined.

The effect of program termination in a freestanding environment is implementation-defined.

The cross-reference to clause 4 Conformance refers to this:

¶5 A strictly conforming program shall use only those features of the language and library specified in this International Standard.3) It shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior, and shall not exceed any minimum implementation limit.

¶6 The two forms of conforming implementation are hosted and freestanding. A conforming hosted implementation shall accept any strictly conforming program. A conforming freestanding implementation shall accept any strictly conforming program in which the use of the features specified in the library clause (clause 7) is confined to the contents of the standard headers <float.h>, <iso646.h>, <limits.h>, <stdalign.h>,
<stdarg.h>, <stdbool.h>, <stddef.h>, <stdint.h>, and
<stdnoreturn.h>. A conforming implementation may have extensions (including
additional library functions), provided they do not alter the behavior of any strictly conforming program.4)

¶7 A conforming program is one that is acceptable to a conforming implementation.5)

3) A strictly conforming program can use conditional features (see 6.10.8.3) provided the use is guarded by an appropriate conditional inclusion preprocessing directive using the related macro. For example:

#ifdef __STDC_IEC_559__ /* FE_UPWARD defined */
    /* ... */
    fesetround(FE_UPWARD);
    /* ... */
#endif

4) This implies that a conforming implementation reserves no identifiers other than those explicitly reserved in this International Standard.

5) Strictly conforming programs are intended to be maximally portable among conforming implementations. Conforming programs may depend upon non-portable features of a conforming implementation.

It is noticeable that the only header required of a freestanding environment that actually defines any functions is <stdarg.h> (and even those may be — and often are — just macros).

Standard C++ — Freestanding Environment

Just as the C standard recognizes both hosted and freestanding environment, so too does the C++ standard. (Quotes from ISO/IEC 14882:2011.)

1.4 Implementation compliance [intro.compliance]

¶7 Two kinds of implementations are defined: a hosted implementation and a freestanding implementation. For a hosted implementation, this International Standard defines the set of available libraries. A freestanding
implementation is one in which execution may take place without the benefit of an operating system, and has an implementation-defined set of libraries that includes certain language-support libraries (17.6.1.3).

¶8 A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that
use such extensions that are ill-formed according to this International Standard. Having done so, however, they can compile and execute such programs.

¶9 Each implementation shall include documentation that identifies all conditionally-supported constructs that it does not support and defines all locale-specific characteristics.3

3) This documentation also defines implementation-defined behavior; see 1.9.

17.6.1.3 Freestanding implementations [compliance]

Two kinds of implementations are defined: hosted and freestanding (1.4). For a hosted implementation, this International Standard describes the set of available headers.

A freestanding implementation has an implementation-defined set of headers. This set shall include at least the headers shown in Table 16.

The supplied version of the header <cstdlib> shall declare at least the functions abort, atexit, at_quick_exit, exit, and quick_exit (18.5). The other headers listed in this table shall meet the same requirements as for a hosted implementation.

Table 16 — C++ headers for freestanding implementations

Subclause                           Header(s)
                                    <ciso646>
18.2  Types                         <cstddef>
18.3  Implementation properties     <cfloat> <limits> <climits>
18.4  Integer types                 <cstdint>
18.5  Start and termination         <cstdlib>
18.6  Dynamic memory management     <new>
18.7  Type identification           <typeinfo>
18.8  Exception handling            <exception>
18.9  Initializer lists             <initializer_list>
18.10 Other runtime support         <cstdalign> <cstdarg> <cstdbool>
20.9  Type traits                   <type_traits>
29    Atomics                       <atomic>

What about using int main() in C?

The standard §5.1.2.2.1 of the C11 standard shows the preferred notation — int main(void) — but there are also two examples in the standard which show int main(): §6.5.3.4 ¶8 and §6.7.6.3 ¶20. Now, it is important to note that examples are not ‘normative’; they are only illustrative. If there are bugs in the examples, they do not directly affect the main text of the standard. That said, they are strongly indicative of expected behaviour, so if the standard includes int main() in an example, it suggests that int main() is not forbidden, even if it is not the preferred notation.

6.5.3.4 The sizeof and _Alignof operators

¶8 EXAMPLE 3 In this example, the size of a variable length array is computed and returned from a function:

#include <stddef.h>

size_t fsize3(int n)
{
    char b[n+3]; // variable length array
    return sizeof b; // execution time sizeof
}
int main()
{
    size_t size;
    size = fsize3(10); // fsize3 returns 13
    return 0;
}

A function definition like int main(){ … } does specify that the function takes no arguments, but does not provide a function prototype, AFAICT. For main() that is seldom a problem; but it does mean that if you have recursive calls to main(), the arguments won’t be checked. For other functions, it is more of a problem — you really need a prototype in scope when the function is called to ensure that the arguments are correct.

You don’t normally call main() recursively, outside of places like IOCCC — and you are explicitly forbidden from doing so in C++. I do have a test program that does it — mainly for novelty. If you have:

int i = 0;
int main()
{
    if (i++ < 10)
        main(i, i * i);
    return 0;
}

and compile with GCC and don’t include -Wstrict-prototypes, it compiles cleanly under stringent warnings. If it’s main(void), it fails to compile because the function definition says «no arguments».

Standard C — Hosted Environment

For a hosted environment (that’s the normal one), the C11 standard (ISO/IEC 9899:2011) says:

5.1.2.2.1 Program startup

The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:

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

or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):

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

or equivalent;10) or in some other implementation-defined manner.

If they are declared, the parameters to the main function shall obey the following
constraints:

  • The value of argc shall be nonnegative.
  • argv[argc] shall be a null pointer.
  • If the value of argc is greater than zero, the array members argv[0] through
    argv[argc-1] inclusive shall contain pointers to strings, which are given
    implementation-defined values by the host environment prior to program startup. The
    intent is to supply to the program information determined prior to program startup
    from elsewhere in the hosted environment. If the host environment is not capable of
    supplying strings with letters in both uppercase and lowercase, the implementation
    shall ensure that the strings are received in lowercase.
  • If the value of argc is greater than zero, the string pointed to by argv[0]
    represents the program name; argv[0][0] shall be the null character if the
    program name is not available from the host environment. If the value of argc is
    greater than one, the strings pointed to by argv[1] through argv[argc-1]
    represent the program parameters.
  • The parameters argc and argv and the strings pointed to by the argv array shall
    be modifiable by the program, and retain their last-stored values between program
    startup and program termination.

10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as
char **argv, and so on.

Program termination in C99 or C11

The value returned from main() is transmitted to the ‘environment’ in an implementation-defined way.

5.1.2.2.3 Program termination

1 If the return type of the main function is a type compatible with int, a return from the
initial call to the main function is equivalent to calling the exit function with the value
returned by the main function as its argument;11) reaching the } that terminates the
main function returns a value of 0. If the return type is not compatible with int, the
termination status returned to the host environment is unspecified.

11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in main
will have ended in the former case, even where they would not have in the latter.

Note that 0 is mandated as ‘success’. You can use EXIT_FAILURE and EXIT_SUCCESS from <stdlib.h> if you prefer, but 0 is well established, and so is 1. See also Exit codes greater than 255 — possible?.

In C89 (and hence in Microsoft C), there is no statement about what happens if the main() function returns but does not specify a return value; it therefore leads to undefined behaviour.

7.22.4.4 The exit function

¶5 Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Standard C++ — Hosted Environment

The C++11 standard (ISO/IEC 14882:2011) says:

3.6.1 Main function [basic.start.main]

¶1 A program shall contain a global function called main, which is the designated start of the program. […]

¶2 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[]) { /* ... */ }

In the latter form argc shall be the number of arguments passed to the program from the environment
in which the program is run. If argc is nonzero these arguments shall be supplied in argv[0]
through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (NTMBSs) (17.5.2.1.4.2) and argv[0] shall be the pointer to the initial character of a NTMBS that represents the
name used to invoke the program or "". The value of argc shall be non-negative. The value of argv[argc]
shall be 0. [Note: It is recommended that any further (optional) parameters be added after argv. —end
note]

¶3 The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. […]

¶5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic
storage duration) and calling std::exit with the return value as the argument. If control reaches the end
of main without encountering a return statement, the effect is that of executing

return 0;

The C++ standard explicitly says «It [the main function] shall have a return type of type int, but otherwise its type is implementation defined», and requires the same two signatures as the C standard to be supported as options. So a ‘void main()’ is directly not allowed by the C++ standard, though there’s nothing it can do to stop a non-standard implementation allowing alternatives. Note that C++ forbids the user from calling main (but the C standard does not).

There’s a paragraph of §18.5 Start and termination in the C++11 standard that is identical to the paragraph from §7.22.4.4 The exit function in the C11 standard (quoted above), apart from a footnote (which simply documents that EXIT_SUCCESS and EXIT_FAILURE are defined in <cstdlib>).

Standard C — Common Extension

Classically, Unix systems support a third variant:

int main(int argc, char **argv, char **envp) { ... }

The third argument is a null-terminated list of pointers to strings, each of which is an environment variable which has a name, an equals sign, and a value (possibly empty). If you do not use this, you can still get at the environment via ‘extern char **environ;‘. This global variable is unique among those in POSIX in that it does not have a header that declares it.

This is recognized by the C standard as a common extension, documented in Annex J:

###J.5.1 Environment arguments

¶1 In a hosted environment, the main function receives a third argument, char *envp[],
that points to a null-terminated array of pointers to char, each of which points to a string
that provides information about the environment for this execution of the program (5.1.2.2.1).

Microsoft C

The Microsoft VS 2010 compiler is interesting. The web site says:

The declaration syntax for main is

 int main();

or, optionally,

int main(int argc, char *argv[], char *envp[]);

Alternatively, the main and wmain functions can be declared as returning void (no return value). If you declare main or wmain as returning void, you cannot return an exit code to the parent process or operating system by using a return statement. To return an exit code when main or wmain is declared as void, you must use the exit function.

It is not clear to me what happens (what exit code is returned to the parent or OS) when a program with void main() does exit — and the MS web site is silent too.

Interestingly, MS does not prescribe the two-argument version of main() that the C and C++ standards require. It only prescribes a three argument form where the third argument is char **envp, a pointer to a list of environment variables.

The Microsoft page also lists some other alternatives — wmain() which takes wide character strings, and some more.

The Microsoft Visual Studio 2005 version of this page does not list void main() as an alternative. The versions from Microsoft Visual Studio 2008 onwards do.

Standard C — Freestanding Environment

As noted early on, the requirements above apply to hosted environments. If you are working with a freestanding environment (which is the alternative to a hosted environment), then the standard has much less to say. For a freestanding environment, the function called at program startup need not be called main and there are no constraints on its return type. The standard says:

5.1.2 Execution environments

Two execution environments are defined: freestanding and hosted. In both cases,
program startup occurs when a designated C function is called by the execution
environment. All objects with static storage duration shall be initialized (set to their initial values) before program startup. The manner and timing of such initialization are otherwise unspecified. Program termination returns control to the execution environment.

5.1.2.1 Freestanding environment

In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. Any library facilities available to a freestanding program, other than the minimal set required by clause 4, are implementation-defined.

The effect of program termination in a freestanding environment is implementation-defined.

The cross-reference to clause 4 Conformance refers to this:

¶5 A strictly conforming program shall use only those features of the language and library specified in this International Standard.3) It shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior, and shall not exceed any minimum implementation limit.

¶6 The two forms of conforming implementation are hosted and freestanding. A conforming hosted implementation shall accept any strictly conforming program. A conforming freestanding implementation shall accept any strictly conforming program in which the use of the features specified in the library clause (clause 7) is confined to the contents of the standard headers <float.h>, <iso646.h>, <limits.h>, <stdalign.h>,
<stdarg.h>, <stdbool.h>, <stddef.h>, <stdint.h>, and
<stdnoreturn.h>. A conforming implementation may have extensions (including
additional library functions), provided they do not alter the behavior of any strictly conforming program.4)

¶7 A conforming program is one that is acceptable to a conforming implementation.5)

3) A strictly conforming program can use conditional features (see 6.10.8.3) provided the use is guarded by an appropriate conditional inclusion preprocessing directive using the related macro. For example:

#ifdef __STDC_IEC_559__ /* FE_UPWARD defined */
    /* ... */
    fesetround(FE_UPWARD);
    /* ... */
#endif

4) This implies that a conforming implementation reserves no identifiers other than those explicitly reserved in this International Standard.

5) Strictly conforming programs are intended to be maximally portable among conforming implementations. Conforming programs may depend upon non-portable features of a conforming implementation.

It is noticeable that the only header required of a freestanding environment that actually defines any functions is <stdarg.h> (and even those may be — and often are — just macros).

Standard C++ — Freestanding Environment

Just as the C standard recognizes both hosted and freestanding environment, so too does the C++ standard. (Quotes from ISO/IEC 14882:2011.)

1.4 Implementation compliance [intro.compliance]

¶7 Two kinds of implementations are defined: a hosted implementation and a freestanding implementation. For a hosted implementation, this International Standard defines the set of available libraries. A freestanding
implementation is one in which execution may take place without the benefit of an operating system, and has an implementation-defined set of libraries that includes certain language-support libraries (17.6.1.3).

¶8 A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that
use such extensions that are ill-formed according to this International Standard. Having done so, however, they can compile and execute such programs.

¶9 Each implementation shall include documentation that identifies all conditionally-supported constructs that it does not support and defines all locale-specific characteristics.3

3) This documentation also defines implementation-defined behavior; see 1.9.

17.6.1.3 Freestanding implementations [compliance]

Two kinds of implementations are defined: hosted and freestanding (1.4). For a hosted implementation, this International Standard describes the set of available headers.

A freestanding implementation has an implementation-defined set of headers. This set shall include at least the headers shown in Table 16.

The supplied version of the header <cstdlib> shall declare at least the functions abort, atexit, at_quick_exit, exit, and quick_exit (18.5). The other headers listed in this table shall meet the same requirements as for a hosted implementation.

Table 16 — C++ headers for freestanding implementations

Subclause                           Header(s)
                                    <ciso646>
18.2  Types                         <cstddef>
18.3  Implementation properties     <cfloat> <limits> <climits>
18.4  Integer types                 <cstdint>
18.5  Start and termination         <cstdlib>
18.6  Dynamic memory management     <new>
18.7  Type identification           <typeinfo>
18.8  Exception handling            <exception>
18.9  Initializer lists             <initializer_list>
18.10 Other runtime support         <cstdalign> <cstdarg> <cstdbool>
20.9  Type traits                   <type_traits>
29    Atomics                       <atomic>

What about using int main() in C?

The standard §5.1.2.2.1 of the C11 standard shows the preferred notation — int main(void) — but there are also two examples in the standard which show int main(): §6.5.3.4 ¶8 and §6.7.6.3 ¶20. Now, it is important to note that examples are not ‘normative’; they are only illustrative. If there are bugs in the examples, they do not directly affect the main text of the standard. That said, they are strongly indicative of expected behaviour, so if the standard includes int main() in an example, it suggests that int main() is not forbidden, even if it is not the preferred notation.

6.5.3.4 The sizeof and _Alignof operators

¶8 EXAMPLE 3 In this example, the size of a variable length array is computed and returned from a function:

#include <stddef.h>

size_t fsize3(int n)
{
    char b[n+3]; // variable length array
    return sizeof b; // execution time sizeof
}
int main()
{
    size_t size;
    size = fsize3(10); // fsize3 returns 13
    return 0;
}

A function definition like int main(){ … } does specify that the function takes no arguments, but does not provide a function prototype, AFAICT. For main() that is seldom a problem; but it does mean that if you have recursive calls to main(), the arguments won’t be checked. For other functions, it is more of a problem — you really need a prototype in scope when the function is called to ensure that the arguments are correct.

You don’t normally call main() recursively, outside of places like IOCCC — and you are explicitly forbidden from doing so in C++. I do have a test program that does it — mainly for novelty. If you have:

int i = 0;
int main()
{
    if (i++ < 10)
        main(i, i * i);
    return 0;
}

and compile with GCC and don’t include -Wstrict-prototypes, it compiles cleanly under stringent warnings. If it’s main(void), it fails to compile because the function definition says «no arguments».

Я работал над книгой «Программирование: принципы и практика с использованием C ++», и этот пример был призван показать, как данные могут быть потеряны при преобразовании типов. Но когда я пытался выполнить его, он все время говорил мне «Main»: должен вернуть значение. Я пытался использовать «return 0;» после фигурной скобки для цикла while, но затем он выдавал ошибки вокруг «Unresolved externals».

Я скопировал код из книги в Visual Studio, и все остальное, что я скопировал, сработало, как и ожидалось — кто-нибудь сможет сказать мне, как я могу это исправить, пожалуйста? Я не знаю, почему это происходит с этим конкретным примером или как заставить его перестать запрашивать возвращаемое значение.

Извините, если это глупо, я очень неопытен, и я попытался найти ответ, но предложенные решения, такие как «return 0», не работают :)!

#include "std_lib_facilities.h"
int main()
{
double d = 0;

while (cin >> d)
{

int i = d;
char c = i;
int i2 = c;
cout << "d==" << d
<< " i==" << i
<< " i2==" << i2
<< " char(" << c << ")n";
}
}

-6

Решение

Я пытался использовать «return 0;» после фигурной скобки для цикла while, но затем он выдавал ошибки вокруг «Unresolved externals».

Это отдельная, не связанная с этим проблема, раскрытая путем исправления первой. Добавьте возврат, затем разберитесь с нерешенной внешней ошибкой.

3

Другие решения

Если это вся ваша программа, вы нерешенный внешний скорее всего iostream, Вы должны включить это и использовать правильное пространство имен.

Рассмотрим следующий код:

#include <iostream>

using namespace std;

int main() {
cout << "Hello World!" << endl;
return 0;
}

Еще лучше отказаться от using заявление и использование std::cout так что вам не нужно беспокоиться о столкновении пространства имен. Смотрите этот вопрос Почему «использование пространства имен std;» считается плохой практикой?

#include <iostream>

int main() {
std::cout << "Hello World!" << std::endl;
return 0;
}

-1

Начнём с заголовочных файлов. Вместо стандартных заголовочных файлов вида <name.h> лучше использовать заголовочные файлы вида <cname>, т.к. первые признаны устаревшими и могут быть удалены в будущих версиях стандарта языка C++. Итак, нам понадобятся:

<cstdio> для std::printf и std::scanf
<clocale> для std::setlocale и макроса LC_ALL
<cmath> для std::sqrt

Функция main должна возвращать значение типа int. Может ли она возвращать значение какого-нибудь другого типа или нет определяется реализацией, поэтому объявим main так:

int main()

Первым аргументом в функцию std::setlocale лучше передать один из специально предназначенных для этого макросов. Например, LC_ALL. Учтите, что одно и тоже целочисленное значение в разных компиляторах может соответствовать разным макросам. Например, в gcc 0 соответствует макросу LC_CTYPE, в то время как в vc++ 0 соответствует макросу LC_ALL.

В C++ в отличие от языка C функция scanf_s не обязана быть объявлена в каком-либо заголовочном файле, поэтому лучше воспользоваться функцией std::scanf. Спецификатор %f говорит, что в scanf необходимо передать указатель на float:

std::scanf("%f %f", &d, &b);

Первым аргументом в функцию std::printf необходимо передать указатель на начальный символ нуль-терминированной строки, задающей что собственно необходимо отобразить и как интерпретировать последующие аргументы. Чтобы вывести значение типа float можно воспользоваться спецификатором преобразования %f:

std::printf("Площадь равна = %f", 0.5 * d * b);

Обратите внимание, что разделитель целой и дробной частей в литерале с плавающей точкой — это точка (.). Итоговый код выглядит примерно так:

#include <cstdio>
#include <clocale>
#include <cmath>

int main()
{
    float d, b, z;
    
    std::setlocale(LC_ALL, "Russian");
    std::printf("Введите два катета: ");
    std::scanf("%f %f", &d, &b);
    z = std::sqrt(d*d + b*b);
    std::printf("Площадь равна = %fn", 0.5 * d * b);
    std::printf("Периметр равен = %fn", d + b + z);
    
    return 0;
}

Есть функция

Код:

int main(int argc, char* argv[])
{
    printf(«Hello!nr»);
    getch();

    return 0;//2005
}

Так вот вопрос, какое значение должна возвращать функция main? Есть какие-либо требования к значению возвращаемому ей? Или это все на совести программиста. К чему Я спрашиваю, поспорил с одним дятлом, что в принципе возвращать можно какое угодно значение типа int и это важно только для родительского процесса(если ему род. процессу нужно анализировать код возврата). На что он мне говорит:

Цитата:

В один прекрасный момент пользователь программы написанной вами скажет,
прошу прощения, какой идиот писал эту прогу.
Возврат 0-ля это этикет 2005 равносильно пошло все на ….
Возврат 0 это правила любого !!!хорошего!!! программиста.

Может Я «нехороший» программист. Кто из нас не прав, может Я и вправду идиот?

28 ответов

8.5K

13 ноября 2005 года

CaveCanem

13 / / 04.01.2005

Можно и так

Код:

void main()
{
 // CODE HERE
}

:)

P.S
Стандарт требует возвращения 0 (нуля) при нормальном завершении и любова интового значения при ошибке.

1

13 ноября 2005 года

kot_

7.3K / / 20.01.2000

Цитата:

Originally posted by CaveCanem

P.S
Стандарт требует возвращения 0 (нуля) при нормальном завершении и любова интового значения при ошибке.

А можно ссылку на статью стандарта?

246

13 ноября 2005 года

GIZMO

1.8K / / 30.07.2004

Цитата:

Originally posted by kot_
А можно ссылку на статью стандарта?

Да было-бы интересно. Сам ничего найти не могу.

246

13 ноября 2005 года

GIZMO

1.8K / / 30.07.2004

Цитата:

Originally posted by CaveCanem
Можно и так

Код:

void main()
{
 // CODE HERE
}

:)

P.S
Стандарт требует возвращения 0 (нуля) при нормальном завершении и любова интового значения при ошибке.

Из хелпа про: The Value main() Returns

The value returned by main is the status code of the program: an int. If, however, your program uses the routine exit (or _exit) to terminate, the value returned by main is the argument passed to the call to exit (or to _exit).

For example, if your program contains the call

exit(1)

the status is 1.

Хоть Я и английского не знаю толком, но что-то про return 0 ничего не слышу, а?

Ну Я допускаю, что Билдер != стандарт, но всеже где это сказано ОБЯЗЯТЕЛЬНО возвразщение 0?

3

13 ноября 2005 года

Green

4.8K / / 20.01.2000

Прямого указания, что должна возвращать main в стандарте нет, но косвенное упоминание есть:
http://www.csci.csusb.edu/dick/c++std/cd2/basic.html#basic.start.main

Цитата:

3.6.1.5
…..
If control reaches the end of main without encountering a return statement, the effect is that of executing
return 0;

Так же о коде возврата говорится в описании exit()
http://www.csci.csusb.edu/dick/c++std/cd2/lib-support.html#lib.support.start.term

Цитата:

18.3.4
…..
— Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned.

Кроме того надо заметить, что возвращаемое значение ноль воспринимается всеми оболочками, как нормальное завершение, а отличное от нуля, как завершение с ошибкой. Например, в DOS отличное от нуля значение воспринимается, как код ошибки, и используется в конструкциях IF ERRORLEVEL и т.п.

246

13 ноября 2005 года

GIZMO

1.8K / / 30.07.2004

Спасибо за ссылки.
А как же тогда общаться с дочерним процессом? Я думал, что то значение которое возвращает main служит для передачи его стартовым кодом в ExitProcess и после завершения дочернего процесса вызовом GetExitCodeProcess(…) мы узнаем чего же он наработал. Или Я не прав?

3

13 ноября 2005 года

Green

4.8K / / 20.01.2000

Цитата:

Originally posted by GIZMO
Спасибо за ссылки.
А как же тогда общаться с дочерним процессом? Я думал, что то значение которое возвращает main служит для передачи его стартовым кодом в ExitProcess и после завершения дочернего процесса вызовом GetExitCodeProcess(…) мы узнаем чего же он наработал. Или Я не прав?

Никто не запрещает тебе возвращать значения из main руководствуясь другим принципом.
Вот только много ли можно вернуть в DWORD ? :)
К тому же, др. программы (не твои) будут неверно трактовать такие коды возврата.

А для общения процессам лучше использовать pipe и т.п.

246

13 ноября 2005 года

GIZMO

1.8K / / 30.07.2004

Цитата:

Originally posted by GIZMO
А как же тогда общаться с дочерним процессом? Я думал, что то значение которое возвращает main служит для передачи его стартовым кодом в ExitProcess и после завершения дочернего процесса вызовом GetExitCodeProcess(…) мы узнаем чего же он наработал. Или Я не прав?

Вот попробовал все работает как Я и думал.

246

13 ноября 2005 года

GIZMO

1.8K / / 30.07.2004

Цитата:

Originally posted by Green
Никто не запрещает тебе возвращать значения из main руководствуясь другим принципом.
Вот только много ли можно вернуть в DWORD ? :)
К тому же, др. программы (не твои) будут неверно трактовать такие коды возврата.

А для общения процессам лучше использовать pipe и т.п.

Так всеже какой вывод: — необходимо возвращать 0 или необязательно? Полагаюсь на твое мнение как на мнение знатока стандартов.
???

2.4K

14 ноября 2005 года

dinasok51

219 / / 12.11.2005

Здесь ссылка на сам стандарт, а не на его интерпретацию

в нем определен лишь код возврата совместимый с int. Все другое не определено.

IMHO необходимость кода вазврата определяет не язык программирования, а среда исполнения — ОС и след. см. док, какова реакция ОС на различные коды завершения твоей прогр.

246

14 ноября 2005 года

GIZMO

1.8K / / 30.07.2004

Цитата:

Originally posted by dinasok51
Здесь ссылка на сам стандарт, а не на его интерпретацию

в нем определен лишь код возврата совместимый с int. Все другое не определено.

IMHO необходимость кода вазврата определяет не язык программирования, а среда исполнения — ОС и след. см. док, какова реакция ОС на различные коды завершения твоей прогр.

А, что там по немецки? Я и по английски-то с трудом понимаю. Все равно спасибо.

3

14 ноября 2005 года

Green

4.8K / / 20.01.2000

Цитата:

Originally posted by dinasok51
Здесь ссылка на сам стандарт, а не на его интерпретацию

Интерпритацию? Что бы это значило?

2.4K

14 ноября 2005 года

dinasok51

219 / / 12.11.2005

Цитата:

Originally posted by GIZMO
А, что там по немецки? Я и по английски-то с трудом понимаю. Все равно спасибо.

GIZMO

Извини, не то скопировал вот ссылка на стандарт
см 5.1.2.2.3

а здесь ссылка на все

Green

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

585

14 ноября 2005 года

honeybeer

297 / / 06.09.2004

Цитата:

Originally posted by Green
Интерпритацию? Что бы это значило?

Вот енто черновики стандарта, наиболее близкие к оному: STD

3

14 ноября 2005 года

Green

4.8K / / 20.01.2000

Цитата:

Originally posted by dinasok51
Под интерпретацией я понимаю изложение официальных документов, часто очень близко к тексту, но это не сам документ

Хм… не знал, что рабочая версия стандарта С++ является интерпретацией стандарта ANSI-C.

Само описание стандарта стоит денег и я не думаю, что кто-то выложит его последнюю версию (тем более в HTML) на всеобщее обозрение (если я ошибаюсь, то поделись ссылкой, плз).
Поэтому я привожу ссылки на РАБОЧИЙ ДОКУМЕНТ, а не на «интерпретацию». Могу заверить, что сам стандарт мало отличается рабочего документа.

Цитата:

Originally posted by GIZMO

Так всеже какой вывод: — необходимо возвращать 0 или необязательно? Полагаюсь на твое мнение как на мнение знатока стандартов.

Как я уже говорил в стандарте прямого упоминания нет, поэтому возвращаемые значения регламентируются скорее не стандартом, а средой выполнения, и скорее даже не ОС, а shell-ом. Известные мне оболочки (DOS-shell, bash, и т.п.) интерпретируют ноль, как удачное завершение, а отличное от нуля, как код ошибки.

3

14 ноября 2005 года

Green

4.8K / / 20.01.2000

Цитата:

Originally posted by dinasok51
Cмотри и наслаждайся

Да спасибо, этот документ у меня есть. Но это версия от 1998 года без корректировки 2003 года.
Кроме того, это не HTML версия, и ссылки на неё, согласись, довольно трудно давать.

Суть топика была иная, так что если хочешь поспорить про различия между стандартом 1998 года и Working Paper 1996 года, то предлагаю сделать это в отдельной ветке.

2.4K

16 ноября 2005 года

dinasok51

219 / / 12.11.2005

Спасибо.

4.8K

16 ноября 2005 года

Jump

128 / / 09.11.2005

ИМХО
1.Запуск приложения — есть вызов его функции int main(…);
2.Кто функцию вызывает — тот ее результат и обрабатывает;
3.ОС не обрабатывает этот результат — если она запускает процесс, скажем так, «не для своих нужд».

3

16 ноября 2005 года

Green

4.8K / / 20.01.2000

Цитата:

Originally posted by Jump
ИМХО
1.Запуск приложения — есть вызов его функции int main(…);
2.Кто функцию вызывает — тот ее результат и обрабатывает;

Ага… startup код, никто другой не имеет права вызывать main. Но обработка результата startup-кодом — это передача его (результата) родительскому процессу.

Цитата:

Originally posted by Jump

3.ОС не обрабатывает этот результат — если она запускает процесс, скажем так, «не для своих нужд».

ОС — это не субъект и не единое целое, у неё нет «своих нужд».

P.S. А к чему твой пост то был?

585

17 ноября 2005 года

honeybeer

297 / / 06.09.2004

Цитата:

Originally posted by Green
Ага… startup код, никто другой не имеет права вызывать main…

Неправда, если выкинуть из проекта поддержку CRT, и назначить точку входа на main, то вызываться будет именно она.

3

17 ноября 2005 года

Green

4.8K / / 20.01.2000

Цитата:

Originally posted by honeybeer
Неправда, если выкинуть из проекта поддержку CRT, и назначить точку входа на main, то вызываться будет именно она.

Это из другой оперы.

246

17 ноября 2005 года

GIZMO

1.8K / / 30.07.2004

Цитата:

Originally posted by GIZMO


Так вот вопрос, какое значение должна возвращать функция main?

И еще в подветждение того, что ОБЯЗАТЕЛЬНО оппонент приводит цитату из книги «… за 21 день». Мне смеяться или плакать? :(

3

17 ноября 2005 года

Green

4.8K / / 20.01.2000

Цитата:

Originally posted by GIZMO
И еще в подветждение того, что ОБЯЗАТЕЛЬНО оппонент приводит цитату из книги «… за 21 день». Мне смеяться или плакать? :(

Я тоже считаю возвращение 0 в случае удачного завершения ОБЯЗАТЕЛЬНЫМ (но не необходимым), но аргументировать это «научно-популяроной» литературой не стал бы… :)

4.8K

17 ноября 2005 года

Jump

128 / / 09.11.2005

Цитата:

Originally posted by Green
ОС — это не субъект и не единое целое, у неё нет «своих нужд».

P.S. А к чему твой пост то был?

Не субьект, но объект — уж точно… Значит «свои нужды» (иненнов в кавычках) у нее вполне есть. В общем все это не суть.
Постом я хотел выразить свое понимание данного вопроса, сформированного на опыте (поэтому и написал ИМХО в самом начале), т.к. я в этом main че только не возвращал — и ничего, ОСь не разу не подавилась :)

14K

19 ноября 2005 года

Муравъед

3 / / 19.11.2005

господи делов то на копейку приведи своему корешку такой прим void main(void)
{
return;
}
и будете догадываться что вернёт return? :D

3

19 ноября 2005 года

Green

4.8K / / 20.01.2000

Цитата:

Originally posted by Муравъед
господи делов то на копейку приведи своему корешку такой прим void main(void)
{
return;
}
и будете догадываться что вернёт return? :D

Вопрос не в том, что вернет return, а что вернет процесс и как это будет интерпретировано окружением. В данном случае он вернет ноль, что во всех известных мне оболочках значит «удачное завершение».

На следующем рисунке показана область ошибки

На следующем рисунке показана область, связанная с ошибками.

Давайте переведем это неправильное значение

Оригинал: предупреждение C4508: «main»: функция должна возвращать значение; «void» тип возврата предполагается
Перевод: Предупреждение C4508: «main»: функция должна возвращать значение, «void» тип возврата

Мы можем заметить, что это не ошибка, а только предупреждение, поэтому мы можем на самом деле игнорировать ее, но если нам нужно ее изменить, как ее следует изменить?

Это означает, что основная функция не возвращает значение, поэтому нам нужно только изменитьконец основной функцииВозврат добавленной стоимостиreturn 0Вот и все.

Проблема была решена здесь

Но одно не ясно:
void main () не требует возвращаемого значения, и мы также знаем, что void main на самом деле является нестандартным способом записи, правильный способ записи должен быть
int main (void) или int main (int argc, char * argv [])
Мы заменяем int main (int argc, char * argv []) на другие формы:
1. Используйте void main для замены, когда мы используем void main для замены, программа не сообщает об ошибке;
2. Вместо этого используйте int main (void), программа сообщает об ошибке.

Таким образом, мы заключаем, что только void main может возвращаться без значения, а другие формы должны возвращаться со значением.

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

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 и как ее исправить?

Я работал над книгой «Программирование: принципы и практика с использованием C ++», и этот пример был призван показать, как данные могут быть потеряны при преобразовании типов. Но когда я пытался выполнить его, он все время говорил мне «Main»: должен вернуть значение. Я пытался использовать «return 0;» после фигурной скобки для цикла while, но затем он выдавал ошибки вокруг «Unresolved externals».

Я скопировал код из книги в Visual Studio, и все остальное, что я скопировал, сработало, как и ожидалось — кто-нибудь сможет сказать мне, как я могу это исправить, пожалуйста? Я не знаю, почему это происходит с этим конкретным примером или как заставить его перестать запрашивать возвращаемое значение.

Извините, если это глупо, я очень неопытен, и я попытался найти ответ, но предложенные решения, такие как «return 0», не работают :)!

#include "std_lib_facilities.h"
int main()
{
double d = 0;

while (cin >> d)
{

int i = d;
char c = i;
int i2 = c;
cout << "d==" << d
<< " i==" << i
<< " i2==" << i2
<< " char(" << c << ")n";
}
}

-6

Решение

Я пытался использовать «return 0;» после фигурной скобки для цикла while, но затем он выдавал ошибки вокруг «Unresolved externals».

Это отдельная, не связанная с этим проблема, раскрытая путем исправления первой. Добавьте возврат, затем разберитесь с нерешенной внешней ошибкой.

3

Другие решения

Если это вся ваша программа, вы нерешенный внешний скорее всего iostream, Вы должны включить это и использовать правильное пространство имен.

Рассмотрим следующий код:

#include <iostream>

using namespace std;

int main() {
cout << "Hello World!" << endl;
return 0;
}

Еще лучше отказаться от using заявление и использование std::cout так что вам не нужно беспокоиться о столкновении пространства имен. Смотрите этот вопрос Почему «использование пространства имен std;» считается плохой практикой?

#include <iostream>

int main() {
std::cout << "Hello World!" << std::endl;
return 0;
}

-1

Понравилась статья? Поделить с друзьями:
  • Ошибка mac адреса дом ру
  • Ошибка mac os x vmware
  • Ошибка mac os is not supported with
  • Ошибка ma5 мегафон что это такое
  • Ошибка ma 0005 в программе запуска epic games