Void main c что это
Перейти к содержимому

Void main c что это

  • автор:

What should we choose Int main(), Void main() & main()?

MOHAMMED CHAND PASHA

In C/C++, main is the starting point to any program execution. All the program execution always starts from the ‘main’ with ‘int’ or ‘void’ are its return type.

void main()

The ANSI standard says ‘NO’ to use of ‘void main’ as its completely wrong. STOP using ‘void main’ from now on.There is nothing like void main() in C++ using it give you error. But in C it generate a warning message.

Compile error:

Warning message:

Output:

Now you should be convinced to avoid void main, if not look at what stroustrup say about it.

Can I write “void main()” in C++?

is not and never has been C++, nor has it even been C. See the ISO C++ standard 3.6.1[2] or the ISO C standard 5.1.2.2.1. A conforming implementation accepts

A conforming implementation may provide more versions of main(), but they must all have return type int. The int returned by main() is a way for a program to return a value to “the system” that invokes it. On systems that doesn’t provide such a facility the return value is ignored, but that doesn’t make “void main()” legal C++ or legal C. Even if your compiler accepts “void main()” avoid it, or risk being considered ignorant by C and C++ programmers.

In C++, main() need not contain an explicit return statement. In that case, the value returned is 0, meaning successful execution. For example:

Note also that neither ISO C++ nor C99 allows you to leave the type out of a declaration. That is, in contrast to C89 and ARM C++ ,”int” is not assumed where a type is missing in a declaration.

is an error because the return type of main() is missing.

In C89, the main without return type has default type int. So, main is similar to int main in C89. But in C99, this is not allowed and one must use int before main (i.e. int main()).

int main()

So according to standard ‘int main’ is the best way to declare main function. Void main() has never been in C/C++ refer ISO C++ standard 3.6.1[2] or the ISO C standard 5.1.2.2.1. for more details. It means that main function returns some integer at the end of the execution.

Above implementations shows main() with and without arguments but both have return type int. The return type int is a way for a program to return a value to the system that invokes it.

In C++, if explicit return statement (return 0) ignored than in that case, the value returned is 0, which means successful execution.

Main function

Every C program coded to run in a hosted execution environment contains the definition (not the prototype) of a function named main , which is the designated start of the program.

int main (void) <body > (1)
int main ( int argc , char * argv [ ] ) <body > (2)
/* another implementation-defined signature */ (since C99) (3)

Contents

[edit] Parameters

argc Non-negative value representing the number of arguments passed to the program from the environment in which the program is run.
argv Pointer to the first element of an array of argc + 1 pointers, of which the last one is null and the previous ones, if any, point to strings that represent the arguments passed to the program from the host environment. If argv [ 0 ] is not a null pointer (or, equivalently, if argc > 0), it points to a string that represents the program name, which is empty if the program name is not available from the host environment.

The names argc and argv stand for «argument count» and «argument vector», and are traditionally used, but other names may be chosen for the parameters, as well as different but equivalent declarations of their type: int main ( int ac, char ** av ) is equally valid.

A common implementation-defined form of main is int main ( int argc, char * argv [ ] , char * envp [ ] ) , where a third argument, of type char ** , pointing at an array of pointers to the execution environment variables, is added.

[edit] Return value

If the return statement is used, the return value is used as the argument to the implicit call to exit() (see below for details). The values zero and EXIT_SUCCESS indicate successful termination, the value EXIT_FAILURE indicates unsuccessful termination.

[edit] Explanation

The main function is called at program startup, after all objects with static storage duration are initialized. It is the designated entry point to a program that is executed in a hosted environment (that is, with an operating system). The name and type of the entry point to any freestanding program (boot loaders, OS kernels, etc) are implementation-defined.

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

The parameters of the two-parameter form of the main function allow arbitrary multibyte character strings to be passed from the execution environment (these are typically known as command line arguments). The pointers argv [ 1 ] .. argv [ argc — 1 ] point at the first characters in each of these strings. argv [ 0 ] (if non-null) is the pointer to the initial character of a null-terminated multibyte string that represents the name used to invoke the program itself (or, if this is not supported by the host environment, argv [ 0 ] [ 0 ] is guaranteed to be zero).

If the host environment cannot supply both lowercase and uppercase letters, the command line arguments are converted to lowercase.

The strings are modifiable, and any modifications made persist until program termination, although these modifications do not propagate back to the host environment: they can be used, for example, with strtok .

The size of the array pointed to by argv is at least argc+1 , and the last element, argv[argc] , is guaranteed to be a null pointer.

The main function has several special properties:

If the main function executes a return that specifies no value or, which is the same, reaches the terminating } without executing a return , the termination status returned to the host environment is undefined.

int main() vs void main() vs int main(void) in C & C++

submit your article

The difference between int main() and int main(void)

Both int main() and int main(void) may look like same at the first glance but there is a significant difference between the two of them in C but both are same in C++.

In C, a function without any parameter can take any number of arguments. For example, a function declared as ‘foo()’ can take any number of arguments in C (calling foo(), foo(1), foo(‘A’,1) will not give any error).

The above code runs fine without giving any error because a function without any parameter can take any number of arguments but this is not the case with C++. In C++, we will get an error. Let’s see.

Running the above code will give us an error because we can’t pass any argument to the function ‘foo’.

However, using foo(void) restricts the function to take any argument and will throw an error. Let’s see.

The above code will give us an error because we have used ‘foo(void)’ and this means we can’t pass any argument to the function ‘foo’ as we were doing in the case of ‘foo()’.

So, both foo(void) and foo() are same in C++ but not in C. The same is the case with ‘main’ function also. So, the preferred form to use is int main(void) if main is not taking any argument.

Difference between int main() and void main() and main()

Like any other function, main is also a function but with a special characteristic that the program execution always starts from the ‘main’. ‘int’ and ‘void’ are its return type. So, let’s discuss all of the three one by one.

1. Структура программы на языке с

Для того чтобы описать структуру программы, написанной на C, рассмотрим простейшую программу, выводящую на экран строку Hello, world.

// Program1.cpp

Void main()

printf(«%s»,»\nHello, world\n»);

В первой строке данной программы находится однострочный комментарий. В приведенном комментарии указано имя файла, в котором хранится исходный текст программы. В С комментарии могут быть заданы двумя способами. Для однострочных комментариев используют символы //, как в нашем примере. Для многострочных комментариев можно использовать символы /* , */, между которыми и должен находится сам текст комментария. В тексте комментария могут содержаться любые символы, а вся последовательность символов эквивалентна символу пропуска (например, символу пробела). Комментарии одного типа не могут быть вложенными, однако можно использовать символы // для того, чтобы закомментировать символы /*… */, а символами /*…*/можно закомментировать //.

Во второй и третьей строке программы помещены команды препроцессора (директивы) #include. Данная декрктива позволяет подключить стандартные библиотеки функций используемого компилятора или оттранслированные модули, написанные самим программистом. Директива #include имеет два формата:

В первом случае имя_файла определяет текстовый (заголовочный) файл, содержащий прототипы (описания) той или иной группы стандартных для данного компилятора функций. Например, в нашем случае директива #include <stdio.h> обеспечивает включение стандартных функций ввода даннях с клавитуры и вывода на экран. Если программист хочет использовать в своей программе такие стандартные функции как косинус (cos), синус (sin), степень числа (pow), то он должен использовать директиву #include <math.h>, для использования функции ожидания ввода любого символа с клавиатуры без отображения на экране, то есть функции задержки экрана (getch) – директиву #include <conio.h>, функцию конкатенации строк (strcat)– директиву #include <string.h>. Если в программе, например, используется функция cos (функция вычисления косинуса), но не указана директива #include <math.h>, то на этапе компиляции возникнет ошибка. Ниже приведено функциональное значение основных заголовочных файлов:

math.h –математические функции;

ctype.h – функции проверки и преобразования символов;

stdio.h – функции ввода–вывода данных;

string.h, stdlib.h – функции для работы со строками;

alloc.h – функции для выделения и освобождения памяти;

conio.h – функции для работы с терминалом в текстовом режиме;

graphics.h – функции для работы с графикой.

Если имя_файла после директивы #include указано в кавычках, это означает, что используется не стандартный заголовочный файл, а файл, созданный самим программистом.

Четвертая строка программы является заголовком функции с именем main. Каждая программа должна содержать функцию с именем main, и работа программы начинается с выполнения этой функции. Перед именем main помещено служебное слово void – спецификатор типа, указывающий, что функция main в данной программе не возвращает никакого значения. Круглые скобки после main требуются в связи с синтаксисом заголовка любой функции и содержат список параметров. В нашем примере параметры не нужны и этот список пуст.

Тело любой функции в языке С – это заключенная в фигурные скобки последовательность описаний и операторов. Каждое описание и оператор заканчивается символом ‘;’. В данном примере в теле функции main нет явных описаний, а есть только один оператор

printf («\nHello, world\n»);

В соответствии с информацией, содержащейся в файле stdio.h, printf является именем функции, который обеспечивает вывод информации на экран монитора. (Поэтому, если строка #include <stdio.h> будет отсутствовать в программе, то имя printfбудет воспринято как неизвестное на этапе компиляции программы). В нашем примере экран будет вывдена это строковая константа «\nHello, world\n». Строковая константа в языке С –это последовательность символов, заключенная в двойные кавычки. В строке символ обратной косой черты ‘\’, за которым следует другой символ, обозначает один специальный символ, в данном случае, ‘\n’ является символом новой строки. Таким образом, выводимые символы в данном случае состоят из символа перевода строки, символов Hello, world и еще одного символа перевода строки.

Отметим, что обратная косая черта ‘\’ позволяет не только записывать символы, не имеющего графического изображения и некоторые другие, но и выводить символьные константы, явно задавая их коды в восьмеричном или шестнадцатеричном виде. Последовательность литер, начинающаяся с символа ‘\’ называют esc–последовательностями (ескейп–последовательностями). Их допустимые значения приведены в таблице 1.

Методы организации вывода и ввода данных будут подробно рассмотрены в главе 3.

Последняя строка программы представляет собой вызов функции gecth() – функции задержки экрана до нажатия пользователем любой клавиши.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *