From WikiChip
Difference between revisions of "c/program structure"
< c

(Reserved Words)
 
(6 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{C Guide}}
+
{{c title|Program Structure}}
Before moving on, it's important to understand the basic structure of a [[C]] program.
+
The way a program is written and its makeup is usually referred to as '''program structure'''. Understanding the general flow a C code is crucial to being able to read and understand any piece of C code.
  
 
== Reserved Words ==
 
== Reserved Words ==
{{main|Reserved words - C|l1=Reserved words}}
+
{{main|c/reserved words|l1=Reserved words}}
C programs are made of a series of grouped characters and symbols known as tokens. [[Reserved words - C|Reserved words]] are a set of words that have special meaning within your [[C]] program. They make up the basic functionality of your program. Reserved words may only be used within their appropriate context - they may be not be used as variable names, or any other type of identifier. We will expand on that later.
+
C programs are made up of a series of grouped characters and symbols known as tokens. {{C|Reserved words}} are a set of words that have special meaning within your [[C]] program; they make up the basic functionality of your program. Reserved words may only be used within their appropriate context - they '''may be not''' be used as ''variable names'', or ''any other type of identifier''; we will expand on that later.
  
== Hello World Example ==
+
== "Hello, World!" Example ==
Let's look at the famous Hello World program. It is very important that you are able to create the program text, compile it, run it, and find the output generated by program.
+
Let's look at the famous "Hello, World!" program. The "Hello, World!" program is very important, in that you are able to create the program text, compile it, run it, and find the output generated by the program. Below is the source code for the "Hello, World!" program:
  
 
<source lang="C">
 
<source lang="C">
Line 19: Line 19:
 
</source>
 
</source>
  
The exact way on how you build and run the program depends on the system and the utilities you are using. For example, if you are using Visual Studio on Windows, all it takes is clicking on the green play button or the Ctrl+F5 shortcut key. If you are using a UNIX or Linux system, you should be able to compile the program using the following command:
+
The exact way on how you build and run the program depends on the system and the utilities you are using. For example, if you are using Visual Studio on Windows, all it takes is clicking on the green play button, or using the Ctrl+F5 shortcut. If you are using a UNIX or Linux system, you should be able to compile the program using the following command:
  
 
  gcc hello.c
 
  gcc hello.c
  
If everything went alright, an executable output file will be generated. Traditionally, the executable has been named 'a.out'. If you received an error during the compilation process double check your code for omitted characters or misspelling. You should be able to run the file by typing:
+
If everything goes as planned, an executable output file will be generated. Traditionally, the executable has been named 'a.out'. If you receive an error during the compilation process, double check your code for omitted characters or misspelling. You should be able to run the file by typing:
  
 
  ./a.out
 
  ./a.out
  
Other systems might have different rules on how you should compile and run the program. Consult the documentation or an expert familiar with your environment.
+
Other operating systems might have different rules on how you should compile and run the program. Consult your operating system's documentation, or an expert familiar with your system's environment, for more detailed information.
  
 
Regardless of the compiler and operating system used, the output should be identical for everyone:
 
Regardless of the compiler and operating system used, the output should be identical for everyone:
Line 34: Line 34:
  
 
=== Program Explanation ===
 
=== Program Explanation ===
Regardless of the size and complexity of a C program. C programs consists of functions and variables. A '''function''' contains statements that specify the operation to be performed. [[Variables - C|Variables]] are a way of naming and storing values for later use by the program.
+
C programs consists of functions and variables.
  
In our example program, main is a function we defined. Normally you would be allowed to name your functions whatever you like, but "'''main'''" happens to be a special function. All C programs begin executing at the beginning of function main. As a corollary, this also means that every program must have a main somewhere.
+
* '''functions''': Contain statements that specify the operation to be performed.
 +
* {{C|Variables}}: A way of naming and storing values for later use by the program.
  
The first line of the program,
+
In our "Hello, World!" example program, main is a function that we defined. Normally, you would be allowed to name your functions whatever you like, but "'''main'''" happens to be a special function. All C programs begin executing at the beginning of function '''main()'''; as a corollary, this also means that every program must have a '''main()''' function somewhere.
 +
 
 +
The first line of our sample program,
  
 
<source lang="C">#include <stdio.h></source>
 
<source lang="C">#include <stdio.h></source>
  
tells the compiler to include information about the standard I/O library. That line is part of the [[Preprocessor - C|pre-processor]].
+
tells the compiler to include information about the standard '''I/O''' (''Input/Output'') library; that line is part of the {{C|preprocessor}}.
  
One of the ways functions can communicate with one another is for the calling function to provide a list of values to the function it calls. These values are called '''[[arguments]]'''. The parenthesis after the function name are used to surround the argument list. In our example, "'''()'''" is used to indicate an empty list of arguments. A function can return a value back to it's caller. The type of value the function returns is specified in front of the function name. In our example we return an int - this is a requirement when you define function main.
+
One way that functions communicate with one another is calling a function in order to provide a list of values to the function being called; these values are called '''[[arguments]]'''. The parenthesis after a function name are used to surround the ''argument list''. In our "Hello, World!" example, "'''()'''" is used to indicate an empty list of arguments. A function has the ability to return a value back to its caller. The type of value a function returns is specified in front of the function name. In our example, we return an <code>int</code> - this is a ''requirement'' when you define function '''main()'''.
  
The statements of a function are enclose in a pair of curly brackets '''{ }'''. The function main contains two statements:
+
The statements of a function are enclosed within a pair of curly brackets, '''{ }'''. The function '''main()''' contains two statements:
  
 
<source lang="C">
 
<source lang="C">
Line 53: Line 56:
 
</source>
 
</source>
  
Generally speaking, every statement in a C program should end with a semicolon.  
+
Generally speaking, every statement in a C program should end with a semicolon, ''';'''.  
  
A function in C is called by simply naming it and adding a list of arguments (if any) in parentheses after it. In our example program,
+
A function, in C, is called by simply naming it and adding a list of arguments (if any) in the parentheses directly after the name. In our example program,
  
 
<source lang="C">puts("Hello, World!");</source>
 
<source lang="C">puts("Hello, World!");</source>
  
calls the function '''puts''' with the argument "Hello, World!". puts is a standard library function that prints output - in this case a string of characters between the double quotes.  
+
calls the function '''puts()''' with the argument "Hello, World!". '''puts()''' is a standard library function that prints output - in this case a string of characters between the double quotes.  
  
In C, a sequence of characters surrounded by double quotes like "Hello, World!" is called a '''[[string constant - C|string constant]]'''. For the time being their only use is to be printed out by the puts function or as argument to other functions.  
+
In C, a sequence of characters surrounded by double quotes like "Hello, World!" is called a '''{{C|string constant}}'''. For the time being, the only use of strings is that they be printed out by the '''puts()''' function, or as argument to other functions.  
  
The last statement of main,
+
The last statement of '''main()''',
  
 
<source lang="C">return 0;</source>
 
<source lang="C">return 0;</source>
  
is the '''return statement'''. The return statement terminates the execution of a function and returns control to the calling function. Because main is the first function to be executed, the control returns to the host environment. A value of '''0''' indicates a successful termination of the program.
+
is the '''return statement'''. The return statement terminates the execution of a function and returns control to the calling function. Because '''main()''' is the first function to be executed, the control returns to the host environment. A value of '''0''' indicates a successful termination of the program.
  
 
== Formatting Style ==
 
== Formatting Style ==
The indentations we used in our code is meant to give us easier time reading and grasping the meaning of the code. Characters space, horizontal tab, new-line, vertical tab, and form-feed are collectively called [[white space]]. Because the compiler works on a series of tokens and ignores all extra white space, you have a considerable amount of freedom concerning how you format your program. C is a [[[free format]] language - the positioning of characters in the source file is insignificant. There are no rules for where you should place brackets or how you should indent your code. As you will see, this is both a blessing and a curse.  
+
The indentations, which we used in our code, are meant to provide us a much more pleasurable visual layout for reading, thus allowing for a better grasp on the meaning of the code. Character spaces, horizontal tabs, new-lines, vertical tabs, and form-feeding are collectively called [[white space]]. Because the compiler works on a series of tokens and ignores all extra white space, you have a considerable amount of freedom concerning how you format your program. C is a [[free-format language]] - the positioning of characters in the source file is insignificant. There are no rules for where you should place brackets or how you should indent your code. As you will see, this is both a blessing and a curse. In fact, the following rewrite of the example program we have above is perfectly legal in C:
 
 
In fact, the following rewrite of the example program we have above is perfectly legal C:
 
  
 
<source lang="C">#include <stdio.h>
 
<source lang="C">#include <stdio.h>
 
int main(){puts("Hello, World!");return 0;}</source>
 
int main(){puts("Hello, World!");return 0;}</source>
  
As well as:
+
Another legal, but ugly, example is:
  
 
<source lang="C">#include <stdio.h>
 
<source lang="C">#include <stdio.h>
Line 95: Line 96:
 
}</source>
 
}</source>
  
You should be able to compile and run both programs. At this point in time you should not be too worried about the formatting of your program. You will develop a style of your own as you continue to learn the language.  
+
You should be able to compile and run both of the above programs. At this point in time, you should not be too worried about the formatting of your program. You will develop a style of your own as you continue to learn the language.  
  
With these two examples in mind we will note that there are many different coding styles in existence. Everyone has an opinion about which is best. Regardless of which one you end up going with, it is extremely important that you keep it consistent.
+
Keeping these two examples in mind, we will note that there are many different coding styles in existence. Everyone has an opinion about which is best. Regardless of which coding style you end up relying on, it is extremely important that you keep it consistent.
  
 
== Comments ==
 
== Comments ==
{{main|Comments - C|l1=Comments}}
+
{{main|c/comments|l1=Comments}}
Even though our hello world example works, it lacks a very important thing: documentation. Every program should be documented enough so that the future you, or more importantly, other programmers know some general things about it like the author, what it does, and perhaps the license associated with it. In C, such information is placed in [[comments - C|comments]]. The characters '''/*''' introduce a comment and the characters '''*/''' terminate it. For example:
+
Even though our "Hello, World!" example works, it lacks one very important thing: documentation. Every program should be documented enough so that in the future you, or, more importantly, other programmers know some general things about, such as: the author, what the program does, and, perhaps, the license associated with the program. In C, such information is placed in {{C|comments}}. The characters '''/*''' introduce a comment and the characters '''*/''' terminate it. For example:
  
 
<source lang="C">/* This is a comment. */
 
<source lang="C">/* This is a comment. */
Line 112: Line 113:
 
*/</source>
 
*/</source>
  
Comments do not change the meaning of the program - they are simply for the programmer's information. Comments are treated as if they were a single space. They may appear almost anywhere in your code. Comments may not appear within character constant, string literals, or other comments. Therefore, comments also do not nest.  
+
'''Comments''' do not change the meaning of a program - they are simply for the programmer's information. Comments are treated as if they were a single space, and they may appear almost anywhere in your code. Comments may not appear within character constants, string literals, or other comments. Therefore, comments can not nest.
  
Here is out hello world example with some comments:
+
Here is our "Hello, World!" example, with some added comments:
  
 
<source lang="C">
 
<source lang="C">
Line 132: Line 133:
  
 
=== Single-line Comments ===
 
=== Single-line Comments ===
[[C99]] introduced a second style of comments which begins with // and terminates automatically at the new-line character.  
+
[[C99]] introduced a second style of comments, which begin with '''//''', and terminate automatically at the new-line character. These comments are referred to as '''Single-line Comments'''.
 +
 
 +
Our "Hello, World!" example program could be written as:
  
Our Hello Example program could be written as:
 
 
<source lang="C">
 
<source lang="C">
 
// Name:        hello.c
 
// Name:        hello.c
 
// Description: Prints "Hello, World!"
 
// Description: Prints "Hello, World!"
// Author:      David Schor
+
// Author:      David
 
#include <stdio.h>
 
#include <stdio.h>
  
Line 147: Line 149:
 
}
 
}
 
</source>
 
</source>
 +
 +
Note how we have replaced the previous comment blocks, '''/* */''', with the '''single-line comments'''.
  
 
[[Category:C programming language]]
 
[[Category:C programming language]]

Latest revision as of 14:16, 9 March 2016

The way a program is written and its makeup is usually referred to as program structure. Understanding the general flow a C code is crucial to being able to read and understand any piece of C code.

Reserved Words[edit]

Main article: Reserved words

C programs are made up of a series of grouped characters and symbols known as tokens. Reserved words are a set of words that have special meaning within your C program; they make up the basic functionality of your program. Reserved words may only be used within their appropriate context - they may be not be used as variable names, or any other type of identifier; we will expand on that later.

"Hello, World!" Example[edit]

Let's look at the famous "Hello, World!" program. The "Hello, World!" program is very important, in that you are able to create the program text, compile it, run it, and find the output generated by the program. Below is the source code for the "Hello, World!" program:

#include <stdio.h>

int main()
{
    puts("Hello, World!");
    return 0;
}

The exact way on how you build and run the program depends on the system and the utilities you are using. For example, if you are using Visual Studio on Windows, all it takes is clicking on the green play button, or using the Ctrl+F5 shortcut. If you are using a UNIX or Linux system, you should be able to compile the program using the following command:

gcc hello.c

If everything goes as planned, an executable output file will be generated. Traditionally, the executable has been named 'a.out'. If you receive an error during the compilation process, double check your code for omitted characters or misspelling. You should be able to run the file by typing:

./a.out

Other operating systems might have different rules on how you should compile and run the program. Consult your operating system's documentation, or an expert familiar with your system's environment, for more detailed information.

Regardless of the compiler and operating system used, the output should be identical for everyone:

Hello, World!

Program Explanation[edit]

C programs consists of functions and variables.

  • functions: Contain statements that specify the operation to be performed.
  • Variables: A way of naming and storing values for later use by the program.

In our "Hello, World!" example program, main is a function that we defined. Normally, you would be allowed to name your functions whatever you like, but "main" happens to be a special function. All C programs begin executing at the beginning of function main(); as a corollary, this also means that every program must have a main() function somewhere.

The first line of our sample program,

#include <stdio.h>

tells the compiler to include information about the standard I/O (Input/Output) library; that line is part of the preprocessor.

One way that functions communicate with one another is calling a function in order to provide a list of values to the function being called; these values are called arguments. The parenthesis after a function name are used to surround the argument list. In our "Hello, World!" example, "()" is used to indicate an empty list of arguments. A function has the ability to return a value back to its caller. The type of value a function returns is specified in front of the function name. In our example, we return an int - this is a requirement when you define function main().

The statements of a function are enclosed within a pair of curly brackets, { }. The function main() contains two statements:

puts("Hello, World!");
return 0;

Generally speaking, every statement in a C program should end with a semicolon, ;.

A function, in C, is called by simply naming it and adding a list of arguments (if any) in the parentheses directly after the name. In our example program,

puts("Hello, World!");

calls the function puts() with the argument "Hello, World!". puts() is a standard library function that prints output - in this case a string of characters between the double quotes.

In C, a sequence of characters surrounded by double quotes like "Hello, World!" is called a string constant. For the time being, the only use of strings is that they be printed out by the puts() function, or as argument to other functions.

The last statement of main(),

return 0;

is the return statement. The return statement terminates the execution of a function and returns control to the calling function. Because main() is the first function to be executed, the control returns to the host environment. A value of 0 indicates a successful termination of the program.

Formatting Style[edit]

The indentations, which we used in our code, are meant to provide us a much more pleasurable visual layout for reading, thus allowing for a better grasp on the meaning of the code. Character spaces, horizontal tabs, new-lines, vertical tabs, and form-feeding are collectively called white space. Because the compiler works on a series of tokens and ignores all extra white space, you have a considerable amount of freedom concerning how you format your program. C is a free-format language - the positioning of characters in the source file is insignificant. There are no rules for where you should place brackets or how you should indent your code. As you will see, this is both a blessing and a curse. In fact, the following rewrite of the example program we have above is perfectly legal in C:

#include <stdio.h>
int main(){puts("Hello, World!");return 0;}

Another legal, but ugly, example is:

#include <stdio.h>
int
main
(
)
{
puts
(
"Hello, World!"
)
;
return
0
;
}

You should be able to compile and run both of the above programs. At this point in time, you should not be too worried about the formatting of your program. You will develop a style of your own as you continue to learn the language.

Keeping these two examples in mind, we will note that there are many different coding styles in existence. Everyone has an opinion about which is best. Regardless of which coding style you end up relying on, it is extremely important that you keep it consistent.

Comments[edit]

Main article: Comments

Even though our "Hello, World!" example works, it lacks one very important thing: documentation. Every program should be documented enough so that in the future you, or, more importantly, other programmers know some general things about, such as: the author, what the program does, and, perhaps, the license associated with the program. In C, such information is placed in comments. The characters /* introduce a comment and the characters */ terminate it. For example:

/* This is a comment. */

/*
and
so 
is
this
*/

Comments do not change the meaning of a program - they are simply for the programmer's information. Comments are treated as if they were a single space, and they may appear almost anywhere in your code. Comments may not appear within character constants, string literals, or other comments. Therefore, comments can not nest.

Here is our "Hello, World!" example, with some added comments:

/*
    Name:        hello.c
    Description: Prints "Hello, World!"
    Author:      John Doe
*/
#include <stdio.h>

int main()
{
    puts("Hello, World!");
    return 0;
}

Single-line Comments[edit]

C99 introduced a second style of comments, which begin with //, and terminate automatically at the new-line character. These comments are referred to as Single-line Comments.

Our "Hello, World!" example program could be written as:

// Name:        hello.c
// Description: Prints "Hello, World!"
// Author:      David
#include <stdio.h>

int main()
{
    puts("Hello, World!");
    return 0;
}

Note how we have replaced the previous comment blocks, /* */, with the single-line comments.