Basic structure of a C program
- Case sensitive
- Free-form lines
/* circle.c - Example C Program
calculates dimensions of circles */
#include <stdio.h>
#define PI 3.141592654
float circum(float diameter);
float area(float radius);
int main()
{
float diameter;
char inbuf[128];
printf("Enter the diameter of a circle: ");
gets(inbuf);
sscanf(inbuf, "%f", &diameter);
printf("The circumference of the circle is: %f\n", circum(diameter));
printf("The area of the circle is: %f\n", area(diameter/2));
return 0;
}
float circum(float diameter)
{
return(PI * diameter);
}
float area(float radius)
{
return(PI * radius * radius); /* pi times radius squared */
}
Comments
/* circle.c - Example C Program calculates dimensions of circles */
The first two lines of the program form a comment. A comment is a note written by the programmer to provide information about the program to other programmers (or to him or herself). A computer program can become rather confusing to look at, and a well placed comment here and there can greatly improve the readability of a program.
The computer ignores comments, so you can use just about anything you want in a comment. In C, a comment begins with a /* and ends with a */. Everything between the beginning and the end of the comment is ignored. In C++, a comment can begin with // and goes on to the end of the line.
Preprocessor Directives
#include <stdio.h> #define PI 3.141592654
Before your C program is interpreted by the compiler, it is passed through the C preprocessor. Preprocessor directives are on lines that begin with a pound sign. The preprocessor obeys these directives and removes them from the program, often replacing them with somethign else, before giving the result to the actual C compiler.
The #include directive tells the preprocessor to read in the specified file and include it in the compilation of the program. The specified file is called a header file. Your C compiler comes with several header files, and you may also write your own. Header files are normally used to describe the built-in library functions (like printf, gets, and sscanf) or functions written by the programmer which are found in other files.
The #define directive defines a macro. A macro is a mechanism by which the preprocessor substitutes one value for another. In this example, the preprocessor will replace all occurances of PI in the program with 3.141592654.