Programming in C is similar to programming in C++; however, there are some differences and we will vew them here.
Like C++, the file is the unit of compilation: any file containing a function main may be compiled into an executable. Program 1 shows the ubiquitous Hello World! program in C.
/*********************************************** * Hello World * * Print 'Hello World!' to the standard output * (by default, the monitor) and exit. ***********************************************/ #include <stdlib.h> #include <stdio.h> int main( void ) { printf( "Hello World!\n" ); return EXIT_SUCCESS; }
In C++, you include the library header iostream; in C, it is the standard input/output header. When C++ introduced namespaces and incorporated these into the header files (together with numerous other chagnes), it differentiated between programs using the old header files #include <iostream.h> and the new header files #include <iostream> by removing the requirement to include the .h. C, however, has not changed. The header stdlib.h is the standard library.
The signature of the main function must either be int main( void ), where void explicitly states that the function does not require access to the command-line arguments, or int main ( int argc, char *argv[] ), which is similar to C++. The formal parameter argc is normally used to indicate the parameter with the argument count while argv indicates the paramter with the argument vvector. The standard forbids int main() (see 5.1.2.2.1 Program startup of the C11 standard), although many compilers will accept it.
Note: The formulat typename f( void ) is used to indicate that the function has no parameters (See 6.7.6.3 Function declarators (including prototypes) of the C11 standard).
The formatted print printf statement accepts a string as an argument where the character \n (line feed) is the end-of-line character; at least, on Unix. The function printf is defined in stdio.h.
The next statement, return EXIT_SUCCESS; indicates that when the main function exits, it should return the value EXIT_SUCCESS. The value EXIT_SUCCESS is defined in stdlib.h on ecelinux as 0 and is used to indicate success; other integer values can be returned to indicate some form of failure, although EXIT_FAILURE is defined as 1 in stdlib.h.
There is an online argument as to whether main should use return n (where n is an integer), return EXIT_SUCCESS and return EXIT_FAILURE, or exit( EXIT_SUCCESS ) and exit( EXIT_FAILURE ). In C++, the answer is clear: the destructor of any local varables declared in main will not be called if exit() is used—the destructors may deallocate resources not allocated to the process by the operating system. For C, the answer is resolved in statement 5.1.2.2.3 Program Termination of the C11 standard which says to use return, as it will automatically call exit with the value that is returned.