Things about the main () function that You don't necessarily know

Source: Internet
Author: User

In a variety of C language books, we can see a variety of main () function writing, it is almost confusing, this is the case? There are two main reasons: one is that with the development and evolution of the C language, the writing of the main () function is constantly changing. In addition, some books are not standardized or misleading.

At first, the main () function was very concise. At that time, C programmers refused to write more than one character. I don't know whether the keyboard quality was poor at that time or because the editor was too bad. C programmers in that era seemed to be surprisingly advocating "Simplicity"-or even "Ultimate simplicity ".

main(){printf("hello,world\n");}

This is The oldest way to write The main () function. K & R is The first C Language source program (1978) in their classic masterpiece "The C Programming Language ). This is the mainstream of that era.

It's almost the same as being naked. Isn't it even the # include <stdio. h>? Not in The first version of The C Programming Language. In that era, the C language does not need to be declared for functions whose return value type is int. However, in the second version (1988) of the book, this program was changed:

#include <stdio.h>main(){printf("hello,world\n");}

Does the rule for a function whose return value type is int need not be declared change? The rule has not changed. What has changed is the concept that people no longer tend to "Simplicity" of code, but tend to clearly understand the ins and outs of each identifier in the code. Starting from C89, it was suggested that a function declaration be required before function calling, but it was not mandatory. In C99, this is mandatory. Because The second edition of The C Programming Language was published on The eve of The publication of The ansi c standard (1989, therefore, this change should also be considered as the tendency of the ansi c standard and the recognition of K & R on the new standard. Although this example does not fully reflect this identity.

Why does it not fully reflect this identity? Because the definition of this main () is not written in the Function prototype method, the main () Function without parameters specified in C90 should be written as follows:

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

But the int can be omitted. C90 treats () as outdated writing without writing any content, although C90 reluctantly tolerates it (The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature .).

Why do we tolerate it? Because many old-fashioned codes are still in use.

What is the main () written according to the C99 standard? Int cannot be omitted in C99. However, we only regard () as obsolete without writing any content, but not completely forbidden. This shows the stubbornness of habit power.

So why does K & R agree with the new standard? Other function definitions and function type declarations in The second version of The C Programming Language are basically changed to The function prototype style. For example, when explaining the parameters of the main () function, K & R converts the original main () function

#include <stdio.h>main(argc,argv)int argc;char *argv[];{/*…… */return 0;}

Changed:

#include <stdio.h>main(int argc, char *argv[]){/*…… */return 0;}

The previous statement is almost extinct today, And the next main () is somewhat strange from today's perspective. The parameters of main () are written in the function prototype style, but it does not write the type of the return value of main (), which gives people a bit new and old. Although it cannot be said that it violates C90 (because C90 allows not to write the int before main (), if the int type of the returned value is written, it meets the requirements of the modern C99 standard.

What is "return 0? This has become commonplace in modern C language. It returns a value to the operating system to indicate the state in which the program ends. However, in another piece of code, K & R seems to go too far:

# Include <stdio. h> main (int argc, char * argv []) {int found = 0 ;/*...... Calculate the value of found */return found ;}

This is really a little unconventional. It seems that the calculation result is returned to the operating system, and it is a little unconventional.

What will happen to the first few main () functions without "return 0? According to the C90 standard, an uncertain int type value will be returned. If you do not care about the value returned, it is OK if you do not write it. However, C99 requires the compiler to help with this "return 0;" during compilation. C99 is not moved to a lazy person on the issue of having to write an int, however, we have moved to lazy practices. Q: If I really don't care about the return value of the main () function, how can I define the return value of main () as the void type? I have seen many books written like this.

#include <stdio.h>void main(){printf("This is a C program.\n");}

This was a wild way of writing before C99, where did it come from. However, this method is common in mainstream textbooks of the past few years. K & R (C language inventor) has never been written like this, And C90 international standards do not recognize this writing. Bjarne Stroustrup (founder of c ++) in his FAQ about C ++, he answered whether "void main ()" can be written () he angrily replied that this method was never used in both C ++ and C. In fact, many C language experts think that "void main ()" is very evil.

Therefore, before C99, this is not in line with the standard writing. Although the function of This Code seems to output "This is a C program.", it is actually not a "C program ".

But sometimes there is no error in writing like this? First, errors in the C language do not necessarily occur during compilation, linking, or running. You may also output a garbage value through compilation, linking, or running, but this does not indicate that your code is correct or meaningful. Second, in some compilers, the program crashes or gets a warning. This indicates that this writing method is at least not universally applicable. It can be said that, if it is not the C99 standard, there is no such way of writing.

Does C99 give a foothold in this writing? In a sense, it may be understandable. Because K & R didn't admit this writing method, C90 didn't admit it at all. Although C99 didn't officially admit it, it left a backdoor for it: "It shall be defined ...... Or in some other implementation-defined manner ". This means that if the compiler explicitly claims to allow the void main () method, C99 will not simply think that this method violates the C Standard as C90.

However, in any case, this method is most often a "dialect" of Some compilers. If there is no special reason, such as simply working in a special environment, in addition, only specific compilers are used without considering program portability. Why not write a universally applicable form?

Since many C language experts think that "void main ()" is very evil, why does C99 tolerate this writing? It is difficult to determine whether C99 is dedicated to "accommodating" this writing in the standard column. In addition to void main (), some other main () function writing methods are excluded from the standard by C90. Now, these writing methods are theoretically possible to comply with the C99 standard.

What other main () functions are available? Many compilers support the following main () Syntax:

int main(int argc, char *argv[], char *env[]){/* */return 0;}

There are three parameters. What is env used? That parameter allows the program to obtain environment variables.

What is environment variable? Simply put, it can be understood as some data recorded by the operating system, such as the computer name, where the operating system is stored, and so on. This information may be used by the application during running, and can be obtained through the env parameter.

What if the compiler does not support the third parameter of main? Standard library functions can also achieve the same purpose.

#include <stdlib.h>char *getenv(const char *name);

Can void main () and int main (int argc, char * argv [], char * env []) Comply with C99 standards? I'm afraid I can't say so. Now I just can't say that these two methods do not conform to the C99 standard. However, it is definite that these two writing methods do not conform to the C90 standard, and the portability of these two writing methods is very poor. The C99 standard is vague here and does not further define the meaning of "implementation-defined manner. Unless the compiler declares that it complies with the C99 standard and permits the two statements, it is a breeze to assert that the two statements comply with the C99 standard.

Some people say that "C99 suggests specifying the main function as the int type" is correct? Obviously not. Because C99 is not absolutely not inclusive of non-int type main (). The correct statement is that C90 requires the return value of the main () function to be int type. However, C90 does not allow the int to be written, while C99 requires the "int" to be written ".

What is the following style?

#include <stdio.h>int main(){printf("This is a C program.\n");return 0;}

This statement is a bit nondescribable. The int type of the returned value is written. This is the same as that of C89 or C99, but () does not write anything and is inconsistent with the standard style. The current standards for writing such statements are acceptable, but they are still acceptable but will be outdated (obsolescent). It is only a matter of time before they are discarded. This method is similar to the method of writing an ancient function parameter:

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

All belong to the history of garbage.

I have seen a getch () statement before "}" of the main () function body. What is the problem? This is the product of the times. In the process of PC transformation from the DOS era to the Windows era, the IDE (mainly TC) developed in the DOS era cannot display output results after running programs, in order to carefully observe the running results after running and then return to the IED interface, the program running time is artificially extended (because getch () will wait for the user to enter a character ). However, this is irrelevant to the structure of main. This statement does not have a general significance, but it will be a right option for outdated IDE. The so-called non-universal meaning means that, first, the real program often does not need this statement, that is, this statement has nothing to do with the program function; second, the getch () function is not a standard function, only some compilers support this statement. Writing this statement on other compilers may not work.

Why not use the standard library function getchar? The getchar () function is slightly different from getch (). The former will display the characters typed by the user on the standard output device, the latter will not display the characters typed by the user, which is closer to "Press Any Key to continue ......" .

Some code writes system ("PAUSE") before the end of the main () function. Does that mean that? Yes. This is also a kind of manual Manufacturing "Please press any key to continue...", it has nothing to do with the program function structure, just to facilitate observation of the output results. However, this method is better than calling getch () because the system () function is a standard library function and each compiler provides support.

There is a saying: "In the latest C99 standard, only the following two definitions are correct :"

int main( void ){ /*  */return 0;}

And

int main( int argc, char *argv[] ){/*  */    return 0;}

Is this true?

This statement is obviously incorrect. However, it can be confirmed that the two definitions are correct. Not only is C99 correct, but C89 is also correct.

There is also a way to write:

int main( void ){return EXIT_SUCCESS;}

What is EXIT_SUCCESS?

Return EXIT_SUCCESS; is equivalent to return 0. EXIT_SUCCESS is a symbolic constant defined in stdlib. h. The returned value indicates that the program exits after the task is completed. Another symbolic constant EXIT_FAILURE defined in stdlib. h is usually used to exit when the program cannot complete the task.

It's so dazzling. Do you need to remember so much? Obviously not necessary. A lot of things are junk due to historical reasons.

What kind of C language should I remember or use? Apparently:

int main( void ){ /*  */    return 0;}

And

int main( int argc, char *argv[] ){/*  */    return 0;}

First, they are widely used and there is no portability problem;

Second, for the moment, they do not have any outdated or expiring ingredients. Of course, if you like elegance, you can also write EXIT_SUCCESS without returning 0. By the way, some learners cannot remember the names of two parameters with the main () function. In fact, the names of these two parameters can also be retrieved by yourself. You don't have to use them as long as you remember the type. The type of the second parameter can also be char **, which is equivalent to the original one.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.