C is a language like any other - in order to make yourself understood, there are rules and conventions to follow. These rules are termed syntax. In a human-human conversation, ambiguities are reduced by body language, tone, context and experience but ambiguities often remain and mistakes are common. Computer languages need to be precise about the meaning of any statement. Ambiguities and confusion cannot be allowed and this is where syntax errors appear.
#include <stdio.h>
main() {
printf("%s","Hello World!\n");
}
Probably the simplest of all C programs. Line by line:
Include the standard I/O library
Every program needs some basic methods - receiving input from the keyboard or files,
producing output to the screen or to files, arithmetic, conversions and other functions.
stdio.h provides the definitions of the basic methods of input and output
for the screen, files and memory. The code to implement each one is built in with the
compiler.
All C programs need a main function.
The function starts with a definition giving the name of the function. You can use
your own function names but the OS will
start execution of the program by calling main() so the file will not compile without one.
As with other languages, functions can take arguments within the parentheses - in this
example, main doesn't take any arguments. It is common for this
first line of the function to also open the function block that contains the code
to execute when the function is executed.
print a formatted string to the default output
printf can handle all your general purpose screen output. (Alternatives
like cout << data do exist but won't be covered here). printf
can output the data as a string "%s", a decimal "%d", or a floating
point number "%f" like 3.141 as well as controlling padding, spaces, decimal
places and sign (positive or negative). printf takes two arguments, the first
defines the output format and the second contains the data to be formatted. The \n
represents a newline character - this will put any further output at the start of the next line.
close the main function block
These are the boring bits of syntax that lead to hassle over syntax rules. A good editor
will help by highlighting problems using colour and links. Make sure all function blocks
are closed, make sure all statements (like the printf statement on line 3)
end in a semi-colon. The most common problem is parentheses in function calls. It is legal
in C to use the output of one function as the input of the next. If you had a function called
myfunc() that returned the "Hello World!" string, you could call
myfunc() within printf():
printf("%s", myfunc());
Note the double parentheses at the end of the statement - one to close myfunc()
and one to close the enclosing printf().
This is part of www.codehelp.co.uk Copyright © 1998-2004 Neil Williams
See the file about.html for
copying conditions.