A simple C Program
#include <stdio.h>
main()
{
printf("Hello, world!\n");
return 0;
}
If you have a C compiler, the first thing to do is figure out how to
type this program in and compile it and run it and see where its output
went.
The first line is practically boilerplate; it will appear in almost all
programs we write. It asks that some definitions having to do with the
"Standard I/O Library'' be included in our program; these definitions
are needed if we are to call the library function printf
correctly.
The second line says that we are defining a function named main. Most of
the time, we can name our functions anything we want, but the function
name main is special: it is the function that will be
"called'' first when our program starts running. The empty pair of
parentheses indicates that our main function accepts no arguments, that is, there isn't any information which needs to be passed in when the function is called.
The braces { and } surround a list of statements in C. Here, they surround the list of statements making up the function main.
The line
printf("Hello, world!\n");
is the first statement in the program. It asks that the function printf be called; printf is a library function which prints formatted output. The parentheses surround printf 's
argument list: the information which is handed to it which it should
act on. The semicolon at the end of the line terminates the statement.
printf 's first (and, in this case, only) argument is
the string which it should print. The string, enclosed in double quotes
(""), consists of the words "Hello, world!'' followed by a special
sequence: \n. In strings, any two-character sequence beginning with the
backslash \ represents a single special character. The sequence \n
represents the "`new line'' character, which prints a carriage return or
line feed or whatever it takes to end one line of output and move down
to the next. (This program only prints one line of output, but it's
still important to terminate it.)
The second line in the main function is
return 0;
In general, a function may return a value to its caller, and main is no exception. When main
returns (that is, reaches its end and stops functioning), the program
is at its end, and the return value from main tells the operating system
(or whatever invoked the program that main is the main function of) whether it succeeded or not. By convention, a return value of 0 indicates success.
Self Assessment Questions
i) The information that needs to be passed in when a function is called is ______
ii) State true or false
The main() function doesn't return any value.
No comments:
Post a Comment