Topic : Introduction to C Programming
Author : Mkoubaa
Page : << Previous 3  Next >>
Go to page :


   printf("%f\n",a);  
}


This code prints out a floating point value since a is declared as type float, but a will be 3.0 because the code performed an integer division.
Operator precedence in C is also similar to that in Pascal. As in Pascal, parentheses control precedence. See tutorial 14 for more information on precedence, which becomes somewhat complicated in C once pointers are introduced.
Typecasting
C allows you to perform type conversions on the fly. You do this especially often when using pointers. Typecasting also occurs during the assignment operation for certain types. For example, in the code above, the integer value was automatically converted to a float.
You do typecasting in C by placing the type name in parentheses and putting it in front of the value you want to change. Thus, in the above code, replacing the line a=10/3; with a=(float)10/3; produces 3.33333 in a because 10 is converted to a floating point value before the division.
Types
You declare named, user-defined types in C with the typedef statement. The following example shows a type that appears often in C code:

#define TRUE  1  
#define FALSE 0
typedef int boolean;

void main()  
{    
    boolean b;
    
    b=FALSE;    
    blah blah blah  
}


This code allows you to declare Boolean types in C programs.
If you do not like the word ``float'' for real numbers, you can say:

typedef float real;

and then later say:

real r1,r2,r3;

You can place typedef statements anywhere in a C program as long as they come prior to their first use in the code. You do not have to group them together as in Pascal, and you need no special word to mark the beginning of the block as in Pascal.
Records
Records in C and Pascal are very similar, as shown below. First, consider a Pascal record.

type    
    rec=record      
        a,b,c:integer;      
        d,e,f:real;    
    end;  
var    
    r:rec;


In C, the same code looks like this:

struct rec  
{    
    int a,b,c;    
    float d,e,f;  
}; /* Note semicolon */

struct rec r;


As shown here, whenever you want to create records of the type rec, you have to say struct rec. This line is very easy to forget, and you get many compiler errors because you absent-mindedly leave out the struct. You can compress the code into the form:

struct rec  
{    
    int a,b,c;    
    float d,e,f;  
} r;


where the type declaration for rec and the variable r are declared in the same statement.
You access fields of records exactly as in Pascal, using a period (.), for example, r.a=5;.
You can declare a typedef for a record. For example, if you do not like saying struct rec r every time you want to declare a record, you can say:

typedef struct rec rec_type;

and then declare records of type rec_type by saying:

rec_type r;

Arrays
You declare arrays by inserting an array size after a normal declaration, as shown below:

int a[10];        /* array of integers */  
char s[100];      /* array of characters (a C string) */  
float f[20];      /* array of reals */  
struct rec r[50]; /* array of records */

Incrementing

Long Way     Short Way
i=i+1;       i++;
i=i-1;       i--;
i=i+3;       i += 3;
i=i*j;       i *= j;


Exercises
Try out different pieces of code to investigate typecasting and precedence. Try out int, char, float, and so on.
Create an array of records and write some code to sort that array on one integer field.
C error to avoid
As described above, using the / operator with two integers will often produce an unexpected result, so think about it whenever you use it.

Introduction to C Programming
Part 6: Functions


Most languages let you create procedures or functions, or both. C allows only functions, although you can create procedures by making functions that return nothing. C functions can accept an unlimited number of parameters. As mentioned in the introduction, they cannot be nested. In general, C does not care in what order you put your functions in the program.
We have already talked a little about functions. The rand function in tutorial 4 is about as simple as a function can get. It accepts no parameters and returns an integer result:

int rand()
/* from K&R - produces a random number between 0 and 32767.*/
{
    rand_seed = rand_seed * 1103515245 +12345;
    return (unsigned int)(rand_seed / 65536) % 32768;
}


The int rand() line declares the function rand to the rest of the program and specifies that rand will accept no parameters and return an integer result. This function has no local variables, but if it needed locals, they would go right below the opening {. (C actually allows you to declare variables after any {. Those variables vanish as soon as the matching } is reached. While they exist, they are placed on the system stack.) Note that there is no ; after the () in the first line. If you accidentally put one in, you will get a huge cascade of error messages that make no sense. Also note that even though there are no parameters, you must use the (). They tell the compiler that you are declaring a function rather than simply declaring an int.
The return statement is important to any function that returns a result. It gives the function the value to return and causes it to exit immediately. This means that you can place multiple return statements in the function to give it multiple exit points. If you do not place a return statement in a function, the function returns when it reaches } and gives you garbage (many compilers will warn you if you fail to return a value). In C, a function can return values of any type.
There are several correct ways to call the rand function---for example: x=rand();. The x is assigned the value returned by rand in this statement. Note that you must use () in the function call, even though no parameter is passed. Otherwise, x is given the memory address of the rand function, which is generally not what you intended.
You might also call rand this way:

if (rand() > 100)

Or this way:

rand();

In the latter case, the value returned by rand is discarded. You may never want to do this with rand, but many functions return some kind of error code through the function name, and if you are not concerned with the error code (for example, because you know that an error is impossible) you can discard it in this way.
You create procedures (in the Pascal sense) by giving the function a void return type. For example:

void print_header()  
{    
    printf("Program Number 1\n");    
    printf("by Marshall Brain\n");    
    printf("Version 1.0, released 12/26/91\n");  
}


This function returns no value, so it is a procedure. You can call it with the following statement:

print_header();

You must include () in the call. If you do not, the function is not called, even though it will compile correctly on many systems.
C functions can accept parameters of any type. For example:

int fact(int i)  
{    
    int j,k;
    
    j=1;
    for (k=2; k<=i; k++)
        j=j*k;    
    return j;  
}


returns the factorial of i, which is passed in as an integer parameter. Separate multiple parameters with commas:

int add (int i, int j)  
{    
    return i+j;  
}


C has evolved over the years. You will frequently see functions such as add written in the "old style," as shown below:

int add(i,j)  
    int i;  
    int j;  
{    
    return i+j;  
}


It is important to be able to read code written in the older style. There is no

Page : << Previous 3  Next >>