Void Main(), Main() and Int Main() in C/C++
Like any other function, the main is also a function but with a special characteristic that the program execution always starts from the main. So the function main needs arguments and a return type. These int and void are its return type. Void means it will not return any value, which is also ok. But if want to know whether the program has terminated successfully or not, we need a return value that can be zero or a non-zero value. Hence the function becomes int main() and is recommended over void main().
If we’re declaring main this way, stop. The definition void main() is not and never has been C++, nor has it even been C. Avoid using it Even if your compiler accepts “void main()”, or risk being considered ignorant by C and C++ programmers.
It is acceptable in C89; the return type, which is not specified, defaults to int. However, this is no longer allowed in C99. main() need not contain an explicit return statement. In that case, the value returned is 0, meaning successful execution. This type of declaration is an error because the return type of main() is missing. main()*…*/> is probably never a good idea.
This is the best way to write main if we don’t care about the program arguments. If we care about program arguments, we need to declare the argc and argv parameters too. We should always define main in this way. Omitting the return type offers no advantage in C89 and will break your code in C99.
The correct signature of the function is:
int main(int argc, char **argv)
The name of the variable argc stands for “argument count”; argc contains the number of arguments passed to the program. The name of the variable argv stands for “argument vector”.
When we return 0 at the end ( while using int as the return type) it tells the OS that the program is functional and is without any error(except logical error), as the main function is called by OS and it returns 0 to the OS.
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!
Чем отличается в c++ int main() от void main().
Т. е. точка выхода.
Можно ее пропустить, конечно, тогда компилятор автоматически добавит return 0; в конец программы.
Это значение передается вызывающему процессу (например, операционной системе) чтобы он «понял», что программа завершена корректно.
по завершении программы ничего не возвращает, что может привести к различным проблемам.
Это можно обойти с помощью функции exit();
Но тем не менее, запись void main() не соответствует стандарту и считается некорректной, и некоторые компиляторы ее не принимают.
Первый вариант может возвращать код ошибки.
Второй вариант не может возвращать код ошибки.
Первый вариант будет компилироваться в любом нормальном компиляторе.
Второй вариант будет редко где компилироваться.
void это функция которая не возвращает значений, а int это целочисленная функция и она возвращает значение то есть return
Не слушайте быдлокодеров. Когда вы пишете Int — вы указываете компьютеру, что вы резервируете место в его памяти, куда функция вернет число в диапазоне от (примерно) минус двух миллиардов до плюс двух миллиардов. Вы часто в жизни с двумя миллиардами что-то считаете? Я вот тоже не часто. Всегда используйте наименьший тип данных, который позволяет использовать задача, тем самым вы рационально используете ресурсы компьютера. А то программисту нужны в программе числа в районе нескольких тысяч, а он в нее эти инты понапихал, и куча памяти просто занята, хотя и не используется.
Когда вы указываете тип возвращаемого значения void, это значит, что вы возвращаете НИЧЕГО. ПУСТОТУ. Вы указываете компьютеру, что ничего в памяти не резервируете. Так же вы в конце main пишете просто return — выйти из функции. Упаси вас бог думать, что функция main по умолчанию что-то там в память записывает, нули всякие, нет, она просто по окончании своей работы дает системе знать, что все, программа завершена. Или передает управление командой строке, если вы работаете в консоли.
main function and program execution
Every C program has a primary function that must be named main . The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.
Several restrictions apply to the main function that don’t apply to any other C functions. The main function:
- Can’t be declared as inline .
- Can’t be declared as static .
- Can’t have its address taken.
- Can’t be called from your program.
The main function signature
The main function doesn’t have a declaration, because it’s built into the language. If it did, the declaration syntax for main would look like this:
int main( void ); int main( int argc, char *argv[ ] ); int main( int argc, char *argv[ ], char *envp[ ] );
The main function is declared implicitly by using one of these signatures. You may use any of these signatures when you define your main function. The Microsoft compiler also allows main to have a return type of void when no value is returned. The argv and envp parameters to wmain can also be defined as type char** . For more information about the arguments, see Argument description.
Remarks
Functions within the source program perform one or more specific tasks. The main function can call these functions to perform their respective tasks. When main calls another function, it passes execution control to the function, so that execution begins at the first statement in the function. A function returns control to main when a return statement is executed or when the end of the function is reached.
You can declare any function, including main , to have parameters. The term «parameter» or «formal parameter» refers to the identifier that receives a value passed to a function. See Parameters for information on passing arguments to parameters. When one function calls another, the called function receives values for its parameters from the calling function. These values are called arguments. You can declare formal parameters to main so that it can receive arguments from the command line using the format shown in the function signature.
When you want to pass information to the main function, the parameters are traditionally named argc and argv , although the C compiler doesn’t require these names. Traditionally, if a third parameter is passed to main , that parameter is named envp . The types for argc , argv , and envp are defined by the C language. You can also declare argv as char** argv and envp as char** envp . Examples later in this section show how to use these three parameters to access command-line arguments. The following sections explain these parameters.
If your code adheres to the Unicode programming model, you can use the Microsoft-specific wide-character version of main , wmain , as your program’s entry point. For more information about this wide-character version of main , see Using wmain .
main termination
A program usually stops executing when it returns from or reaches the end of main , although it can terminate at other points in the program for various reasons. For example, you may want to force the termination of your program when some error condition is detected. To do so, you can use the exit function. For more information on exit and an example of usage, see exit .
main function and program execution
Every C program has a primary function that must be named main . The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.
Several restrictions apply to the main function that don’t apply to any other C functions. The main function:
- Can’t be declared as inline .
- Can’t be declared as static .
- Can’t have its address taken.
- Can’t be called from your program.
The main function signature
The main function doesn’t have a declaration, because it’s built into the language. If it did, the declaration syntax for main would look like this:
int main( void ); int main( int argc, char *argv[ ] ); int main( int argc, char *argv[ ], char *envp[ ] );
The main function is declared implicitly by using one of these signatures. You may use any of these signatures when you define your main function. The Microsoft compiler also allows main to have a return type of void when no value is returned. The argv and envp parameters to wmain can also be defined as type char** . For more information about the arguments, see Argument description.
Remarks
Functions within the source program perform one or more specific tasks. The main function can call these functions to perform their respective tasks. When main calls another function, it passes execution control to the function, so that execution begins at the first statement in the function. A function returns control to main when a return statement is executed or when the end of the function is reached.
You can declare any function, including main , to have parameters. The term «parameter» or «formal parameter» refers to the identifier that receives a value passed to a function. See Parameters for information on passing arguments to parameters. When one function calls another, the called function receives values for its parameters from the calling function. These values are called arguments. You can declare formal parameters to main so that it can receive arguments from the command line using the format shown in the function signature.
When you want to pass information to the main function, the parameters are traditionally named argc and argv , although the C compiler doesn’t require these names. Traditionally, if a third parameter is passed to main , that parameter is named envp . The types for argc , argv , and envp are defined by the C language. You can also declare argv as char** argv and envp as char** envp . Examples later in this section show how to use these three parameters to access command-line arguments. The following sections explain these parameters.
If your code adheres to the Unicode programming model, you can use the Microsoft-specific wide-character version of main , wmain , as your program’s entry point. For more information about this wide-character version of main , see Using wmain .
main termination
A program usually stops executing when it returns from or reaches the end of main , although it can terminate at other points in the program for various reasons. For example, you may want to force the termination of your program when some error condition is detected. To do so, you can use the exit function. For more information on exit and an example of usage, see exit .