Monday 2 May 2011

C Program Structure

C Program Structure

A C program basically has the following form:

* Preprocessor Commands
* Type definitions
* Function prototypes -- declare function types and variables passed to function.
* Variables
* Functions

We must have a main() function.

A function has the form:

type function_name (parameters)
{
local variables
C Statements
}

If the type definition is omitted C assumes that function returns an integer type. NOTE: This can be a source of problems in a program.

So returning to our first C program:

/* Sample program */

main()
{
printf( ``I Like C $\backslash$n'' );
exit ( 0 );
}
NOTE:
* C requires a semicolon at the end of every statement.
* printf is a standard C function -- called from main.
* $\backslash$n signifies newline. Formatted output -- more later.
* exit() is also a standard function that causes the program to terminate.

Strictly speaking it is not needed here as it is the last line of main() and the program will terminate anyway.

Let us look at another printing statement:
printf(``.$\backslash$n.1$\backslash$n..2$\backslash$n...3$\backslash$n'');

The output of this would be:
.
.1
..2
...3

Variables

C has the following simple data types:

The Pascal Equivalents are:

On UNIX systems all ints are long ints unless specified as short int explicitly.

NOTE: There is NO Boolean type in C -- you should use char, int or (better) unsigned char.

Unsigned can be used with all char and int types.

To declare a variable in C, do:

var_type list variables;

e.g. int i,j,k;
float x,y,z;
char ch;

Defining Global Variables

Global variables are defined above main() in the following way:-

short number,sum;
int bignumber,bigsum;
char letter;

main()
{

}

It is also possible to pre-initialise global variables using the = operator for assignment.

NOTE: The = operator is the same as := is Pascal.

For example:-

float sum=0.0;
int bigsum=0;
char letter=`A';

main()
{

}

This is the same as:-

float sum;
int bigsum;
char letter;
main()
{
sum=0.0;
bigsum=0;
letter=`A';
}

...but is more efficient.

C also allows multiple assignment statements using =, for example:

a=b=c=d=3;

...which is the same as, but more efficient than:

a=3;
b=3;
c=3;
d=3;

This kind of assignment is only possible if all the variable types in the statement are the same.

You can define your own types use typedef. This will have greater relevance later in the course when we learn how to create more complex data structures.

As an example of a simple use let us consider how we may define two new types real and letter. These new types can then be used in the same way as the pre-defined C types:

typedef real float;
typedef letter char;

Variables declared:
real sum=0.0;
letter nextletter;

Printing Out and Inputting Variables

C uses formatted output. The printf function has a special formatting character (%) -- a character following this defines a certain format for a variable:


%c -- characters
%d -- integers
%f -- floats

e.g. printf(``%c %d %f'',ch,i,x);

NOTE: Format statement enclosed in ``...'', variables follow after. Make sure order of format and variable data types match up.

scanf() is the function for inputting values to a data structure: Its format is similar to printf:

i.e. scanf(``%c %d %f'',&ch,&i,&x);

NOTE: & before variables. Please accept this for now and remember to include it. It is to do with pointers which we will meet later (Section 17.4.1).

Constants

ANSI C allows you to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed.

The const keyword is to declare a constant, as shown below:

int const a = 1;
const int a =2;

Note:

* You can declare the const before or after the type. Choose one an stick to it.
* It is usual to initialise a const with a value as it cannot get a value any other way.

The preprocessor #define is another more flexible (see Preprocessor Chapters) method to define constants in a program.

You frequently see const declaration in function parameters. This says simply that the function is not going to change the value of the parameter.

The following function definition used concepts we have not met (see chapters on functions, strings, pointers, and standard libraries) but for completenes of this section it is is included here:

void strcpy(char *buffer, char const *string)

The second argiment string is a C string that will not be altered by the string copying standard library function.

Arithmetic Operations

As well as the standard arithmetic operators (+ - * /) found in most languages, C provides some more operators. There are some notable differences with other languages, such as Pascal.

Assignment is = i.e. i = 4; ch = `y';

Increment ++, Decrement -- which are more efficient than their long hand equivalents, for example:-- x++ is faster than x=x+1.

The ++ and -- operators can be either in post-fixed or pre-fixed. With pre-fixed the value is computed before the expression is evaluated whereas with post-fixed the value is computed after the expression is evaluated.

In the example below, ++z is pre-fixed and the w-- is post-fixed:

int x,y,w;
main()
{
x=((++z)-(w--)) % 100;
}

This would be equivalent to:

int x,y,w;
main()
{
z++;
x=(z-w) % 100;
w--;
}

The % (modulus) operator only works with integers.

Division / is for both integer and float division. So be careful.

The answer to: x = 3 / 2 is 1 even if x is declared a float!!

RULE: If both arguments of / are integer then do integer division.

So make sure you do this. The correct (for division) answer to the above is x = 3.0 / 2 or x= 3 / 2.0 or (better) x = 3.0 / 2.0.

There is also a convenient shorthand way to express computations in C.

It is very common to have expressions like: i = i + 3 or x = x*(y + 2)

This can written in C (generally) in a shorthand form like this:

$\mbox{{\em expr}}_{1} \: \mbox{{\em op}} \: = \:\mbox{{\em expr}}_{2}$

which is equivalent to (but more efficient than):

$\mbox{{\em expr}}_{1} \: = \: \mbox{{\em expr}}_{1} \: \mbox{{\em op}} \: \mbox{{\em expr}}_{2}$

So we can rewrite i = i + 3 as i += 3

and x = x*(y + 2) as x *= y + 2.

NOTE: that x *= y + 2 means x = x*(y + 2) and NOT x = x*y + 2.

Comparison Operators

To test for equality is ==

A warning: Beware of using ``='' instead of ``=='', such as writing accidentally

if ( i = j ) .....

This is a perfectly LEGAL C statement (syntactically speaking) which copies the value in "j" into "i", and delivers this value, which will then be interpreted as TRUE if j is non-zero. This is called assignment by value -- a key feature of C.

Not equals is: !=

Other operators < (less than) , > (grater than), <= (less than or equals), >= (greater than or equals) are as usual.

Logical Operators

Logical operators are usually used with conditional statements which we shall meet in the next Chapter.

The two basic logical operators are:

&& for logical AND, || for logical OR.

Beware & and | have a different meaning for bitwise AND and OR ( more on this later in Chapter 12).

Order of Precedence

It is necessary to be careful of the meaning of such expressions as a + b * c

We may want the effect as either

(a + b) * c

or

a + (b * c)
All operators have a priority, and high priority operators are evaluated before lower priority ones. Operators of the same priority are evaluated from left to right, so that

a - b - c

is evaluated as

( a - b ) - c

as you would expect.

From high priority to low priority the order for all C operators (we have not met all of them yet) is:


( ) [ ] -> .
! $\sim$ - * & sizeof cast ++ -
(these are right->left)
* / %
+ -
< <= >= >
== !=
&
$\wedge$ |
&&
||
?: (right->left)
= += -= (right->left)
, (comma)

Thus

a < 10 && 2 * b < c

is interpreted as
( a < 10 ) && ( ( 2 * b ) < c )

and

a =

b =
spokes / spokes_per_wheel
+ spares;
as
a =
( b =
( spokes / spokes_per_wheel )
+ spares
);

No comments:

Post a Comment

VMware Cloud Learning Video's

Here is a nice summary list of all VMworld US 2018 Breakout session with the respective video playback & download URLs. Enjoy! Bra...