Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Jack H.Integration and automation of manufacturing systems.2001.pdf
Скачиваний:
80
Добавлен:
23.08.2013
Размер:
3.84 Mб
Скачать

page 43

3. AN INTRODUCTION TO C/C++ PROGRAMMING

3.1 INTRODUCTION

The C programming language was developed at Bell Laboratories in the Early 1970’s. The language was intended to provide a high level framework for data and functions while allowing highly efficient programs. By the 1980s the language had entered widespread usage and was in use for the development of many high level programs. By the 1990s most new software projects were written in C. Some of the advantages of C are listed below.

Machine Portable, which means that it requires only small changes to run on other computers.

Very Fast, almost as fast as assembly language.

Emphasizes structured programming, by focusing on functions and subroutines.

You may easily customize ’C’ to your own needs.

Suited to Large and Complex Programs.

Very Flexible, allows you to create your own functions.

More recently C++ was developed to add object-oriented capabilities to C. In simple terms

the object oriented extensions allow data and functions to be combined together. In general the

advantages that C++ add over C are those listed below. In general, any C program can be com-

piled with C++, while C++ programs will often not compile with a C compiler.

Reusable source code can reduce duplication

Encapsulation of data and functions reduces errors

It is easy to interchange software modules

ASIDE: The expression object-oriented has been misused recently. This was a particular problem with those marketing software. In truth, these techniques are mainly of use only to the programmer. From the users perspective, they will be unaware of whether the souce code of the program is object-oriented or not.

page 44

This chapter will act as a basic introduction or review of C and C++ programming. C programming is discussed first to lay the foundations, and this is followed with a discussion of C++ programming extensions. The end of the chapter discusses structured program design techniques. If you are already fluent in C and C++ I suggest you skip this chapter.

3.2 PROGRAM PARTS

C programs are basically simple text programs that follow a general set of rules (syntax). Figure 3.1 shows the classic beginners program that will add two numbers and print the result. The first line in this example is a comment. Comments are between ’/*’ and ’*/’ can stretch over many lines. Comments can also be the end of a line if they follow ’//’. The ’main()’ program declaration indicates where the program starts. The left and right curly brackets ’{’ and ’}’ are used to group together a set of program statements, in this case the program. Notice that the program statements are indented to indicate how they are grouped. This is a very valuable structuring technique that makes the programs much easier to read.

/* A simple program to add two numbers and print the results */

main() {

int x, y = 2, z; // define three variables and give one a value x = 3; // give another variable a value

z = x + y; // add the two variables

printf(“%d + %d = %d\n”, x, y, z); // print the results

}

Results (output): 3 + 2 = 5

Figure 3.1 - A Program to Add Two Numbers (and results)

The program begins with the definition of three variables, ’x’, ’y’ and ’z’. All three are defined to be ’int’ integers and the value of ’y’ is set to ’2’. The statement is terminated with a

page 45

semicolon to separate it from the next statement. The next line assigns a value of ’3’ to ’x’. The following line adds the values of ’x’ and ’y’ and assigns the value to ’z’. The last statement in the program, ’printf’, prints the values with a format statement. The first string in the command is a format string. In the string a ’%d’ indicates an integer, and ’\n’ indicates an end of line. The remaining characters in the format string are printed as shown. The format string is followed by the variables in the format string, in the same sequence. The result of the program shown that when it is run it prints ’3 + 2 = 5’.

Some of the general rules that are worth noting are listed below.

lower/UPPER case is crucial, and can never be ignored.

Statements can be on one or more lines but must be separated by semi-colons ‘;’.

Statements consist of one operation, or a set of statements between curly brackets {, }

There are no line numbers.

Lines may be of any length.

The data types for C are listed below with typical data sizes. Sometimes these sizes may be larger or smaller. Their behavior of ’char’, ’short’, ’int’ and ’long’ can be modified when preceded with ’unsigned’. For example an integer ’x’ defined with ’int x;’ could have a value from - 32768 to 32767, but if defined with ’unsigned int x;’ it can have a value from 0 to 65535.

char (1 byte ascii character), short (1 byte signed integer), int (2 byte signed integer), long (4 byte signed integer),

float (4 byte floating point IEEE standard), double (8 byte floating point IEEE standard).

Beginners will often write a program in a single ’main’ function. As the program becomes more complex it is useful to break the program into smaller functions. This makes it easier to write and read. Figure 3.2 contains an example program that uses subroutines to perform the same function as the program in Figure 3.1. As before the ’main()’ program function is the starting point for program execution. The subroutine ’add’ is defined after ’main’, so a function prototype is required before. A prototype just indicates the values that are passed, and the function return type. In this example the values 3 and 2 are passed to the ’add’ function. In the add function these values are then put into ’a’ and ’b’. The values are then added and assigned to ’c’. The value of ’c’

page 46

is then returned to the main function where it is assigned to ’z’.

/* A simple program to add two numbers and print the results */

int add(int, int); /* Declare a integer function called ‘add’ */

main() {

int x = 3, y = 2, z; /* define three variables and give values */ z = add(x, y); /* pass the two values to ‘add’ and get the sum*/ printf(“%d + %d = %d\n”, x, y, z); /*print the results */

}

int add(int a, int b) { /* define function and variable list */ int c; /* define a work integer */

c = a + b; /* add the numbers */

return(c); /* Return the number to the calling program */

}

Figure 3.2 - Program to add numbers with a function:

Every variable has a scope. This determines which functions are able to use that variable. If a variable is global, then it may be used by any function. These can be modified by the addition of static, extern and auto. If a variable is defined in a function, then it will be local to that function, and is not used by any other function. If the variable needs to be initialized every time the subroutine is called, this is an auto type. static variables can be used for a variable that must keep the value it had the last time the function was called. Using extern will allow the variable types from other parts of the program to be used in a function.

/* A simple program to add two numbers and print the results */

int x = 3, /* Define global x and y values */ y = 2,

add(); /* Declare an integer function called ‘add’ */

main() {

printf(“%d + %d = %d\n”, x, y, add()); /*print the results */

}

int add() { /* define function */

return(x + y); /* Return the sum to the calling program */

}

Figure 3.3 - Program example using global variables:

page 47

Other variable types of variables are union, enum and struct. Some basic control flow statements are while(), do-while(), for(), switch(), and if(). A couple of example programs are given below which demonstrate all the ’C’ flow statements.

/* A simple program to print numbers from 1 to 5*/

main() {

int i;

for(i = 1; i <= 5; i = i + 1){

printf(“number %d \n”, i); /*print the number */

}

}

Figure 3.4 - Program example with a for loop:

main() { // A while loop int i = 1; while(i <= 5){

printf(“number %d \n”, i); i = i + 1;

}

}

main() { // A do-while loop int i = 1;

do{

printf(“number %d \n”, i); i = i + 1;

}while(i <= 5)

}

Figure 3.5 - Examples of Other Loops

main() {

int x = 2, y = 3; if(x > y){

printf(“Maximum is %d \n”, x); } else if(y > x){

printf(“Maximum is %d \n”, y);

} else {

printf(“Both values are %d \n”, x);

}

}

Figure 3.6 - An If-Else Example

page 48

main(){

int x = 3; /* Number of People in Family */ switch(x){ /* choose the numerical switch */ case 0: /* Nobody */

printf(“There is no family \n”); break;

case 1: /* Only one person, but a start */ printf(“There is one parent\n”); break;

case 2: /* You need two to start something */ printf(“There are two parents\n”); break;

default: /* critical mass */

printf(“There are two parents and %d kids\n”, x-2); break;

}

}

Figure 3.7 - A Switch-Case Example

#include <filename.h> will insert the file named filename.h into the program. The *.h extension is used to indicate a header file which contains ‘C’ code to define functions and constants. This almost always includes “stdio.h”. As we saw before, a function must be defined (as with the ‘add’ function). We did not define printf() before we used it, this is normally done by using

#include <stdio.h> at the top of your programs. “stdio.h” contains a line which says ‘int printf();’. If we needed to use a math function like y = sin(x) we would have to also use #include <math.h>, or else the compiler would not know what type of value that sin() is supposed to return.

#define CONSTANT TEXT will do a direct replacement of CONSTANT in the program with

TEXT, before compilation. #undef CONSTANT will undefine the CONSTANT.

#include <stdio.h> #include <math.h>

#define TWO_PI 6.283185307 #define STEPS 5

main() {

double x; /* Current x value*/

for(x = 0.0; x <= TWO_PI; x = x + (TWO_PI / STEPS)){ printf(“%f = sin(%f) \n”, sin(x), x);

}

}

Figure 3.8 - A More Complex Example

page 49

#fictive, #finder, #if, #else and #else can be used to conditionally include parts of a program. This is used for including and eliminating debugging lines in a program. Statements such as

#define, #include, #fictive, #finder, #if, #else, /* and */ are all handled by the Preprocessor, before the compiler touches the program. Matrices are defined as shown in the example. In ‘C’ there are no limits to the matrix size, or dimensions. Arrays may be any data type. Strings are stored as arrays of characters.

i++ is the same as i = i + 1.

#include “stdio.h” #define STRING_LENGTH 5

main() {

int i;

char string[STRING_LENGTH]; /* character array */ gets(string); /* Input string from keyboard */ for(i = 0; i < STRING_LENGTH; i++){

printf(“pos %d, char %c, ASCII %d \n”, i, string[i], string[i]);

}

}

INPUT:

HUGH<return>

OUTPUT:

pos 0, char H, ASCII 72 pos 1, char U, ASCII 85 pos 2, char G, ASCII 71 pos 3, char H, ASCII 72 pos 4, char , ASCII 0

Figure 3.9 - Printing ASCII Values

Pointers are a very unique feature of ‘C’. First recall that each variable uses a real location in