The C Programming Language

Prepared by: Kamal Zamli
Pusat Pengajian Elektrik Elektronik,
Universiti Sains Malaysia,
Nibong Tebal
Pulau Pinang, Malaysia.
Universiti Sains Malaysia, ASTS Fellowship
First Edition : Advanced Diploma Student ( July-Dis 1995)
Second Edition: Advanced Diploma Student (Jan-Jun 1996)
Third Edition: B Eng Student (July-Dis 1996)
Suggestion and Comments are welcomed. A bit of
history, this notes were used for my C and C++
class from 1995 to 1996 (KJE431)!!! Back then
I was a lecturer at Dept of Electrical Eng in UITM
Part I- The C Programming Language
Part II- Numerical Techniques
Grading
No make up test will be given.
Words of Advise
BSD (Berkeley Standard Distribution) UNIX operating system and cc compiler
will be used in this course. Because of its popularity, notes on the implementation
of C in the MSDOS environment ie Turbo C++ is also included particularly
on the hardware interfacing examples program.
This notes is ;of
the whole course. Some of the details are skipped but will be covered during
the class hour. A number of numerical techniques and simulation will also
will be covered in this course. Please work hard. I will NOT accept last
minute changes to project title.
Table of Contents
1.0 Introduction
2.0 Unix Basics
3.0 Details of typical C program
4.0 Common standard input/output ( printf ()
& scanf()
5.0 Data types in C
6.0 C operators
7.0 Control Statement & Looping
8.0 Functions
9.0 Macro
10.0 RS232 Interfacing with C for MS DOS environment Turbo C++
11.0 Programming with mouse (MSDOS environment)(Interrupt 33h)
12.0 C Common Library (string manipulation & File I/O using C)
13.0 Common C/C++ programming pitfalls.
1.0 Introduction
Dennis Ritchie of Bell Labs created C in 1972 as he and Ken Thompson
worked together designing the Unix operating system. C is actually derived
from Thompson's B language. C and its counterpart C++ offers many advantages
over its other counterparts like PASCAL, BASIC, FORTRAN, COBOL, and etc.
Among the advantages of C are:
2.0 Unix Basics
The following are the most common UNIX commands.
Read file cat filename or more filename Change or edit file vi filename or textedit filename Print file lpr filename Make a copy cp filename newname Mail file mail loginname < filename Remove file rm filename Move file mv filename directoryname/newfilename Count words wc filename Search for keyword grep 'keywords' filename Combile files cat file1 file2 Append files cat file < file2 Get help man command Find specified file find / -name 'filetosearch' -print
For
more UNIX help/tutorial click here
2.1 The Visual Editor (Vi)
UNIX editor is not as straight forward as PC editor. One of the most
common UNIX editor is the vi.
Vi operates in two modes:
To get in to command mode always press the escape key.
Below are the most common Vi keys:
Cursor Positioning Keys in the Command Mode. h moves cursor to the left j moves cursor down one line k moves cursor up one line l moves cursor to the right ^b backward a screen ^f forward a screen $ go to end of line 0 go to first of line G go to end of file N go to the beginning of file /pat search forward for a pattern ?pat search backward for a pattern Enter moves cursor down to the beginning of the next line ma marks the beginning of a block mb marks the end of a block dd delete line dw delete words y yank a line (yank does not delete the originals) D delete to the end of line Commands to Enter in the Text Input Mode . a appends text after the cursor i insert text before the cursor o opens new line below the cursor,ready for text input O opens new line above the cursor, ready for text input R replaces characters on the screen, starting at the cursor with any character you type. Leaving the vi Editor Esc:w Writes the contents of the buffer into the current file of the same name. Can be given a new filename to write to. Also , can send partial buffer contents using line numbers, such as :3,10w popcorn. Esc:w Quits buffer after the command Esc:wq Writes and quits, placing buffer contents in file. Esc:q! Quits buffer without making changes in file. Dangerous. Esc ZZ Writes and quits,placing buffer contents in file. Esc:'a,'b co. Copies the marked block to the cursor location Esc:'a,'b mo. Moves the marked block to the cursor location Esc:'a,'b d Deletes the marked block. Esc:/%s/pat/pat1/g Find pat and replace with pat1 without confirmation Esc:/%s/pat/pat1/gc Find pat and replace with pat1 with confirmation
The cc and CC compiler In the UNIX environment,
CC compiler is the C++ version of the compiler and the cc compiler is its
C counter part. In general, C++ compilers like CC also compiles C program.
When a program is compiled, the object file and the executable file will
be created. The syntax of the command line compiler (cc/CC) is the following:
%CC -o <outputfilename> <filename.c> -g.
The executable file outputfile will be produced.
Example: %CC -o execute prog1.c -g
Note -g is for debugging information for the use of the sparc DBX. We
will be using the SUN sparcworks debugging tools
C/C++ program structure

Example : The first C program
#include <stdio.h>/*include section */
void printyear (void);
int year; /* global variables*/
int main () /* function main */
{
printyear ();
return 0;
}
void printyear(void)
{
int lastyear,thisyear;
thisyear = 1998;
lastyear = 1997;
printf ("\n %d is the year I started learning C& ",thisyear);
printf ("\n %d is last year. \n",lastyear);
}
3.0 Details of typical C/C++ program
3.1 Include section
C users refer to a collection of information that goes at the top of the
file as the header files. C implementations typically come with several
header files. The effect of including,for example, include <stdio.h>,
is the same as if we were to copy the entire contents(library functions)
of the stdio.h file into our file at the position the line appears. In
this case, the function printf is one of the functions library in stdio.h
file.
3.2 Function prototype(s) section
Function prototypes are required in every top down C programming. This
is the most common styles of C program. The function prototypes lists all
the functions that is used and implemented by the current program. Please
note that, some of the old version of C compiler does not support the top
down approach.
3.3 Global/local variable(s) section
A C program must declare the variable before it is used in the program.
An identifier may be any sequence of characters (usually with some length
restrictions) which obeys the following three rules :
In particular, C is case sensitive; making the variable Average, AVERAGE,
and aVeRaGe all different. Note, global variables are declared outside
of functions. The data type used must be of predefined in C/C++ or enumerated
types.
Keywords are vocabulary of C. They can't be used for variable names.
Among C keywords includes:
| auto | break | case | continue | default | union |
| do | double | else | enum | extern | unsigned |
| float | for | goto | if | int | void |
| long | register | return | short | signed | volatile |
| sizeof | static | struct | switch | typedef | while |
3.4 Main section
A C program consist of one or more C functions. Every C/C++ program
must contain a function called main ( ), because that is the function called
when the program starts up.A simple function consists of a header, followed
by an opening brace, followed by the statements constituting the function
body, followed by a terminating closing brace. Each C statement is an instruction
to the computer and is marked by a terminating semicolon. A declaration
statement creates a name for a variable and identifies the type of data
to be stored in the variable.An assignment statement assigns a value to
a variable, or more generally, to a storage area. A function call statement
causes the named function to be executed. When the call funtion is completed,
the program returns to the next statement after the function call.
3.5 Function (s) section
Here the function(s) that are listed in the function prototypes section,
are implemented. Remember that all function(s) must return value. i.e non
return value function returns void.
4.0 Common standard input/output ( printf () & scanf () )
The printf and the scanf function are the standard built in C library
to write/display and read to standard input/output. Both function uses
the ANSI C conversion specification for writing/displaying and reading
to standard input/output.
ANSI C conversion specifications
%c single character
%d signed decimal integer
%e Floating - point number, e-notation
%E Floating - point number, E - notation
%f floating - point number, decimal notation
%g Use %f or %e, whichever is shorter
%G Use %f or %E, whichever is shorter
%i Signed decimal integer
%o Unsigned octal integer
%p Pointer
%s Character string
%u Unsigned decimal integer
%x Unsigned hexadecimal integer, using hex digits a-f
%X Unsigned hexadecimal integer, using hex digits A-F
ANSI C escape sequence
\a alert
\b backspace
\f formfeed
\n newline
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\' single quote
\" double quote
Example: Using the ANSI conversion specification /escape sequence
#include <stdio.h>/*include section */
int main ()
{
char *name; /* name is a string */
int age; /* age is an integer */
printf ("Enter your name ?\n");
scanf ("%s",name); /* notice no ampersand when reading name */
printf ("Enter your age ?\n");
scanf ("%d",&age); /* ampersand is there */
printf ("Welcome %s and %d is still young \n",name,age);
return 0; /* int function must return int */
}
5.0 Data types in C
| Data Types | Bytes Size | Range | Examples |
| char | 1 | -128 to 127 | 'A','!' |
| signed char | 1 | -128 to 127 | '23','C' |
| unsigned char | 1 | 0 to 255 | 0x1A,10 |
| int | Depend on system | -32768 to 32767 for 16 bit | 3000 |
| unsigned int | Depend on system | 0 to 65535 for 16 bit | 0xFFFF |
| short int | 2 | -32768 to 32767 | 100 |
| unsigned short int | 2 | 0 to 65535 | 0xFF |
| long int | 4 | -2147483648 to 2147483648 | 0xffff |
| unsigned long int | 4 | 0 to 4294967295 | 123456 |
| float | 4 | 3.4E-38 to 3.4E38 and -3.4E-38 to -3.4E+38 | 2.35,-52.34 |
| double | 8 | 8 1.7E-308 to 1.7E+308 and -1.7E-308 to -1.7E +308 | -2.5e+100,-78.32544 |
| long double | 10 | 1.2E -4932 to 1.2E+4932and -1.2E-4932 to -1.2E+4932 | 8.5E-3000 |
Example : declaration of variables using predefined data types.
5.1 Enumerated data types in C
The enumerated type lets programmers define symbolic names to represent integer constants, to enhance program readability.
Example : Enumerated data type declaration enum colors { red,blue,green,black }; enum colors color; /* for C++ enum keyword is optional in variable declaration*/In this case red will have a value of 0, blue will have a value of 1 and etc.
5.2 Pointers
A pointer is a variable that hold and address of some data, rather than the data itself. The use of pointer is usually closely related to manipulating (assigning or changing) the elements of and array of data. Pointer are used primarily for three purposes:
Two special pointer operators are required to effectively manipulate pointers:
. Pointer in C is easy as long as one remembers one simple rule of thumb that is pointer can only be assigned to a pointer itself ( of the same kind, or of type void) and to and address of a variable.
Example :Pointer in action ...
int main()
{
int i,*ptr; i=7; ptr = &i; /* ptr points to i */
printf ("\n%d",i);/* display 7 */
printf ("\n %d",*ptr); /* display 7 */
*ptr =11; /* i and *ptr = 11 */
printf ("\n %d %d",*ptr,i);
return 0;
}
Example: String and pointers... char *name; char *name1="Ali"; // initialization during declaration strcpy (name,"fadzil"); /* assignment name="fadzil" is not proper*/
Unlike other programming language, assignment involving string quite tricky at run time. Simply assigning for example, name="fadzil" is not acceptable. A standard C function strcpy must be used (located in string.h). As an alternative one can use a one to one assignment. It is interesting to note that C automatically appends '\0' at the end of every string.
Example: One to one assignment
char *p;
char *name="maliki";
char *copyname;
p=name;
while (*p!='\0')
{
copyname[i]=*p;
p++;
i++;
}
5.3 Structures
The general form declaration of an N element structure is as follows: struct tag_name { type1 element_name1; type2 element_name2; . . typeN element_nameN; } variable_name
Example: Example of structure
struct students { char *name; int age; }
struct students Group1; /* In C++ the keyword struct is unnecessary*/
struct students *Grp;
...
strcpy(Group1.name,"Mohd Asri");
Group1.age=26;
Grp=&Group1; /* Necessary to initialize the string */
strcpy(Grp->name,"Mohd Asri"); /* accessing the element using pointer */
Grp->age=26;
5.4 Array
The general form declaration is as follows: datatype var_name [] ;
Example: Example of array declaration
struct students Group1[10]; /* declare array of structure Group1 */
int days[7]={1,2,3,4,5,6,7};
char name1[]; /* declare array of char i.e string */
char *name2 ;/* also declare array of char i.e string */
char name3[3]; /* declaring array of char of 3 char long */
int number [3][3] /* array 3 x 3, 2 dimension */
Example: Accessing array using subscript & pointer;
int data[2]= {100,300}
int moredata[2]={100,300};
...
int *p1,*p2,*p3;
p1=p2=&data; /* notice the rule of thumb */
p3=moredata; /* ditto */
printf ("%d %d %d\n",(*p1)++,*(++p2),*++p3);
printf ("%d %d %d\n",*p1,*p2,*p3);
printf ("%d %d ",data[1],data[2]);
...
As an exercise predict the output of the above program !!!.
6.0 Operators
List of C operators
| Operators | What it does ? |
| * | multiplication |
| / | division |
| - | substraction |
| % | modulus ( remainder after division) |
| < | less than |
| <= | less than or equal to |
| == | equal to |
| >= | greater than or equal to |
| > | greater thatn |
| != | not equal to |
| && | logical AND |
| || | logical OR |
| ! | logical NOT |
| ++ | increment |
| -- | decrement |
| >> | shift right |
| << | shift left |
| ^ | exclusive OR |
Bit Wise operators
| Operators | What it does |
| ~ | ones complement |
| & | bitwise AND |
| | | bitwise OR |
| ^ | bitwise exclusive OR |
| << | left shift |
| >> | right shift |
6.1 Usage of bit operation:
-Turning one bit on and others off.
Flag = 0xFF;// 11111111
Mask = 0x01;//00000001
Flag & Mask will set bit 0 to 1 and set all other bit to 0.
-Turning one bit off and leaving others unchanged
Flag = 0xFF; // 11111111
Mask=0x08; // 00001000
Flag & ~Mask will turn bit 3 off and leaving other bit unchanged.
-Toggling bits - turn it on if it is off, and turn it off if it is on
Flag = 0xFF;// 11111111
Mask=0x08;// 00001000
Flag ^ Mask will turn bit 3 off if it is on. To turn it on if it is off,
perform the exclusive or operation again.
-Left shift <<
Flag = 0xAF; // 10101111
Flag<< 2 will left shift Flag to 10111100
- Right shift >>
Flag= 0xAF; // 10101111
Flag >> 3 will right shift Flag to 00010101
-Testing for bits
~ Flag = 0x1F; //10101111
if (Flag & 0x10) is true then bit 4 is set.
7.0 Control Statements & Looping
7.1 Conditional Execution:if ..else
The if statement has the following generic format:
if (test condition)
statement1;
else statement2;
When more than one statement needs to be executed if a particular value is true, a compound statement is used. A compound statement consists of a left brace ({) , some number of statements (each ending with semicolon), and a right brace ({).
Example: Using the if statement
if (result > 0)
{ /* positive outputs */
if (result > delta) out= 1; /* assignment statement */
else out = 0;
} else
{ /* other that positive outputs */
if (result <-delta) out = -2;
else out = -1;
}
Example: Confusing if statement
return (a>b) ? a:b; /* this is the most confusing to beginner!!! */
if ( a > b ) /* this is its equivalent statement that less confusing*/
return a;
else
return b;
7.2 The case & switch statement
The basic form of the switch statement is as follows:
switch (integer expression)
{
case constant1:
statement;
break;
case constant2:
statement;
break; ....................
default:
statement;
}
Example: Case statement in action
char c;
...
switch(c)
{
case 'a':
printf ("a \n");
i++;
break;
case 'b':printf("b\n");
i++;
break;
case '@':DONE=TRUE;
break;
default: i=0;
break;
}
7.3 while loop
If the test expression is true, the execution of the program goes inside the while loop. The while loop repeats the statements until the test expression become false. The basic form of the while loop is:
while (test expression)
{ statement;
} /* braces are necessary only for compound statement */
Example:While loop in action
int main ()
{ int n = 0;
while (n < 3)
{
printf ("\n Hoi ... Maliki... error %c \n",0x7);
n++;
}
printf ("Says who \n ");
}
7.4 do while loop
The do while loop also works as the while loop. In the do loop the statement inside the do while loop will be executed at least once eventhough the test expression is false. The basic form of the do while loop is:
do
{ statement;
} while (test expression)
Example:The do while loop
int number;
...
do
scanf("%d",&number);
while (number != 20);
7.5 for loop
The for loop combines an initialization statement, an end condition statement may be a single statement , a compound statement or just a semicolon (a null statement). The basic form of the for loop is:
for (initialize; test condition;end update)
{
statement;
statement;
} /* braces is unnecessary for non compound statement */
Example: The for loop
...
int main ()
{ int counter;
for (counter = 1; count<= 10;count++)
{
printf ("\nI love ITM \n");
printf ("Where I used to study\n");
}
}
8.0 Functions
All C/C++ program consist of one or more function. Even the program executed first is a function called main( ).A C/C++ function may or may not return a value.Any function can call any other function, or called by any other function.C/C++ always passes functions "by value" not "by reference".To pass variable "by reference" the C/C++ programmer must specify the function argument as a pointer.
8.1 Defining and declaring functions
The general format is as follows:
datatype functionname (formal argument)
{
statement;
}
The data type determines the type of value the function returns, not the type of arguments. If no data type is specified, the function is assumed to return an int. If a function does not return a value, it should be declared with the type void.
Example:Function returning an integer value #include#include int x,y,z; int larger_of(int a, int b); int main() /* the main () function returns type int */ { puts("enter two different integer values: "); scanf("%d%d", &x,&y); // note &address of z = larger_of(x,y); printf("\n The larger value is %d. ", z); } return 0; } int larger_of(int a, int b) /* the larger_of function returns type int */ { if ( a > b ) return a; else return b; }
8.2 Storage Class, Privacy and Scope.
In addition to type, variable and functions have a property called storage class. There are three storage classes with three storage class designators: auto for automatic variables stored on the stack,extern for external variables stored outside the current module, static for variables known only in the current module.
Auto variables can only be declared within a function, are created when the function is invoked and are lost when the function is exited. Auto variable are known only to the function in which they are declared and do not retain their value from one invocation of a function to another.Because auto variable are store on a stack, a function that use only auto variable can call itself recursively. The auto keyword is rarely used in C programs since variable declared within function default to the auto storage class. Extern variable have broadest scope. They are known to all function in a module and are even known outside of the module in which they are declared. Extern variables are stored in their own separate data area and must declared outside of any function. Static variables differ from extern variables only in scope. Static variables declared outside of a function in one module is known only to the functions in that module. A static variables declared inside a function is known only to the function in which it is declared.
8.3 Passing parameter to function by refence
By default C passes parameter by value. To pass parameter by reference pointer must be used.
Example:The swap program
void swap (int *x1,*x2)
{
int temp;
temp = *x1;
*x1=*x2;
*x2=temp;
}
...
int main ()
{
int p=1,q=2;
printf ("%d %d",p,q);/* print 1 2 */
swap (&p,&q); /* Note the ampersand &, address of */
printf ("%d %d",p,q); /* print 2 1 */ return 0;
return 0;
}
9.0 C Macro
Some function can be implemented using macros for speed. Function call will use up code segment stack, whereas macro does not. The macro call will be replaced by the actual codes and gets appended to the final executable file. The rule of thumb to use macro is when the function called involved some formulae. Remember, all macros can be converted to function and not all function can be converted to macros.
Example: using ordinary function
float square (float x)
{
return x*x;
}
Example: using Macro
#define SQUARE (x) (x)*(x) // brackets are neccessary to avoid side effect
#define FORMULA (y) (y)*(sin(y)) 10.0
10.0 RS232 Interfacing with C for MS DOS environment Turbo C++
Among the featuresof C that surpasses other language are:
The example given below is the most useful when programming the serial port. Feel free to copy it,for educational use, but please dont claim credit.
Example: Acessing Port Using Turbo C++ ( Library)
/* Only works with COM 1, to use COM2 or etc the address must be specified in */ /* each parts of the routines, i.e COM2 0x2F8 */
/* Part of the codes are adopted from The Book DOS Programmers Reference */
#include <stdio.h>
#include <bios.h>
#include <dos.h>
#include <conio.h>
#include <string.h>
#include <process.h>
#define COM2 1
#define COM1 0
#define DATA_READY 0x100
void port_init (int port,char code );
void send_port (int port,char c);
void send_port_direct (int port,char c);
int receive_port(int port);
int receive_port_direct (int port);
int check_status (int port ); // Initializing the com port
// Tested OK
void port_init (int port,char code )
{ union REGS r;
r.x.dx=port;
r.h.ah=0;
r.h.al=code;
int86(0x14,&r,&r);
}
// send character to port
// Tested OK.. Meant to be used for slower access & response equipment
void send_port (int port,char c)
{ union REGS r;
r.x.dx=port;
r.h.ah=1;
r.h.al=c; int86(0x14,&r,&r);
if (r.h.ah & 0x80)
{
printf ("Error sending %c to the serial port \n",c);
if (kbhit()) exit(1);
}
}
// Direct access to the port level
void send_port_direct (int port,char c)
{ #define LSR 5
#define THR 0
#define THRRDY 0x20
int address;
register int cnt;
if (port==COM1)
address=0x3F8;
if (port==COM2)
address=0x2F8;
cnt=0;
while (!(inportb(address+LSR) & THRRDY) && cnt <10000)
cnt++;
if (cnt>=10000)
{
printf ("Error sending %c to the serial port\n",c);
exit (0);
}
outportb(address+THR,c);
}
// Check status of the serial port
int check_status (int port )
{ union REGS r;
r.x.dx=port;
r.h.ah=3;
int86(0x14,&r,&r);
return r.x.ax;
}
// Receive from the serial port
int receive_port (int port)
{ union REGS r;
while (!check_status(port)& 0xFF)
if (kbhit())
{
getch();
exit (1);
}
r.x.dx=port;
r.h.ah=2;
int86(0x14,&r,&r);
if (r.h.ah & 0x80)
{
printf ("Error receiving character from the port \n");
if (kbhit())
exit(1);
}
return r.h.al;
}
// Receive directly from the specific address
int receive_port_direct(int port)
{ #define RDR 0
#define MASK 0x7F
int address;
if (port==COM1)
address=0x3F8;
if (port==COM2)
address-0x2F8;
return (inportb(address+RDR)&MASK);
}
11.0 Programming with mouse (MSDOS environment) (Interrupt 33h)
/* Demonstrates the most basic mouse function */
#include <conio.h>
#include <stdio.h>
#include <dos.h>// prototypes
int initialize_mouse();
void reset_mouse ();
void show_mouse_pointer ();
void hide_mouse_pointer();
void get_mouse_position (int *x, int *y, int *mousebutton);
void show_mouse_coordinate();
void clear_mouse_coordinate ();
union REGS iReg, oReg;
struct SREGS segregs;
int c, numbuttons, oldmouse, mousebutton, movx, movy; float mouseversion;
int Quit;
int x,y,Buttons,OldX,OldY;
void main ()
{ _setcursortype (_NOCURSOR);
clrscr();
gotoxy (15,5);cputs ("Mouse Movement Demonstration Program");
gotoxy (15,6);cputs ("Written For PDRM staff by Kamal Zamli");
show_mouse_pointer();
gotoxy(18,9);puts("*****************************************");
gotoxy (18,10);puts("Click Here to Quit");
gotoxy(18,11);puts("**************************************");
Quit=0;
OldX=-1;
OldY=-1;
while (!Quit)
{
get_mouse_position(&x,&y,&Buttons);
if ((OldX != x) || (OldY != y))
{
clear_mouse_coordinate();
show_mouse_coordinate();
OldX=x;
OldY=y;
}
if (((x>=15) & (x<=35)) & ((y==9)) & (Buttons==1))
{
Quit=1;
}
}
hide_mouse_pointer();
reset_mouse();
clrscr();
_setcursortype (_NORMALCURSOR);
}
void clear_mouse_coordinate()
{
hide_mouse_pointer();
gotoxy (25,1); puts (" ");
gotoxy (25,2); puts (" ");
show_mouse_pointer();
}
void show_mouse_coordinate ()
{
char xstring[10],ystring[10];
hide_mouse_pointer();
sprintf (xstring,"x = %d",x);
sprintf (ystring,"y= %d",y);
gotoxy (25,1);puts (xstring);
gotoxy (25,2);puts (ystring);
show_mouse_pointer();
}
int initialize_mouse ()
{
iReg.x.ax = 0;
int86(0x33, &iReg, &oReg);
if (oReg.x.ax == 0xFFFF)
return (oReg.x.bx);
else return 0;
}
void reset_mouse ()
{
iReg.x.ax = 0;
int86 (0x33, &iReg,&oReg);
}
void show_mouse_pointer ()
{
iReg.x.ax = 1;
int86 (0x33,&iReg, &oReg);
}
void hide_mouse_pointer ()
{
iReg.x.ax = 2;
int86(0x33, &iReg, &oReg);
}
void get_mouse_position (int *x, int *y,int *mousebutton)
{
iReg.x.ax = 3;
int86 (0x33, &iReg, &oReg);
*x = oReg.x.cx / 8;
*y = oReg.x.dx / 8;
*mousebutton = oReg.x.bx;
}
12.0 C Common Library (string manipulation & File I/O using C)
Example: using common string functions
#include <stdio.h>
#include <string.h>
int main()
{
char *string;
strcpy(string,"hello");/* string="hello" is not allowed */
printf("%s\n", string);
strcat (string,"...dude"); /* append .. dude to string */
strrchr (string,'e'); /* search for the char e */
strstr (string,"dud"); /* search for a sub string in a string */
strlwr (string); /* convert to lower case */
strupr (string);/* convert to upper case */
strset (string,'x'); /* set string to just x's */
return 0;
}
Example: Using malloc () and gets () to allocate storage space of string #include <stdio.h>
#include <alloc.h>
#include <stdlib.h>
int main()
{
char *string;
string = (char* ) malloc (10);
printf("Input a string:");
gets(string);
printf("The string input was: %s\n",string);
return 0;
}
Example : Using common file I/O operation /* Create backup text file */
#include <stdio.h>
int main()
{
FILE *in, *out;
if ((in = fopen("\\AUTOEXEC.BAT", "rt"))== NULL)
{
fprintf(stderr, "Cannot open input file.\n");
return 1;
}
if ((out = fopen("\\AUTOEXEC.BAK", "wt"))== NULL)
{ fprintf(stderr, "Cannot open output file.\n");
return 1;
}
while (!feof(in)) /* feof check for end of file */
fputc(fgetc(in),out); /* fputc put char in the file */
fclose(in);
fclose(out);
return 0;
}
Example: Reading from text file
#include <stdio.h>
#include <stdlib.h>
int main ()
{ FILE *fp;
int i;
float x[10]; // array 0..9 of float
if ( (fp=fopen("c:\\tc\\bin\\data.dat","r")) ==NULL)
{
printf("Error in opening data file \n");
exit (1);
}
i=0;
while (!feof(fp))
{
fscanf (fp,"%f",&x[i]); /* read from text file */
printf ("%.2f\n",x[i]); /* print with 2 decimal places */
i++;
}
return 0;
}
13.0 Common C/C++ programming pitfalls.
Belows are the most common C errors:
1. Misplacing a semicolon.
Example:
if (j==100); /* a null statement ? */ j=0;
/* j will always sets to 0 due to misplace semicolon */
2.Confusing the operator = with ==
Example:
if (a=2) /* this is an assignment statement !!!!*/
printf ("Your turn\n");
3.Confusing a character constant and a character string.
Example:
textchar='a';/* a single character , declared as char */ textstring="a" /*a single string, declared as pointer to char *char */
4.Using the wrong bounds for an array
Example:
int a[100],i,sum=0; ....
for (i=1;i<=100;++i) /* wrong, C array starts from 0, not 1*/
sum +=a[i]; /* in this case a goes from 0..99 */
5.Forgetting to reserve an extra location in an array for the terminating null character of a string. The character string "hello"
requires a declaration of 6 character long array of char because every
string must have a null character at the of the string.
6.Confusing the operator -> with operator >, or >>, when refering structure members. Remember the operator . is used for structure variables, while -> is used for structure pointer variables.
Example:
struct students
{
char *name; int age;
}
int shifting=1;
struct students lists; /* in C++ the keyword struct can be omitted */
struct students *listpntr;
.....
listpntr=&lists;
strcpy(list.name,"ahmad"); strcpy(listpntr->.name,"ahmad");
shifting= shifting<<2 /* shift left ot shifting <<=2 *, shifting
= 4/
7.Omitting the ampersand (&) before non-pointer variables in a scanf call.
Example: int number; ... scanf ("%d",number)
/*error here number should be &number */
Remember that all arguments appearing after the format string in a scanf call must be pointers.
8.Omitting the break statement at the end of a case in a switch statement.
Remember that if a break is not included at the end of a case, then execution
will continue into the next case.
9.Inserting a semicolon at the end of preprocessor definition particularly define.
Example: #define PI 3.14; /* error !!! no semicolon necessary */
Note another way of defining constant is as follows:
const Pi = 31.4;
10.Using expression that has side effects in a macro call.
Example: #define SQUARE (x) (x)*(x) ... W= SQUARE(++v);
The invocation of the SQUARE macro will cause v to be incremented twice,
since this statement will be expanded by the preprocessor to W=(++v)*(++v)
11.Not putting the braces where it is necessary. This error usually happens
when dealing with while,for, and do while statement.
Example: Error using while
n = 0;
while (n<3)
printf ("\n n is %d",n); /* infinite loop , should have braces*/ n++;
Reference:
The folowing books directly and indirectly have contributed to the development of this homepage and notes. As a disclaimer, I will not be responsible for any damages, lost of profit or any disasters as a result of using this notes.
1.Unix Primer Plus, Mitchell Waite,Martin and Stephen Prata,Howard W.
Sams & Company
2.Turbo C++ User Manual, Borland International
3. Programming in C, Stephen G. Kochan, Hyden Books.
4. C Language Algorithms for Digital Signal Processing,Bruce Kimberly,
Prentice Hall Inc.
5. Power C User Manual, Mix Software
6. Dos Programmers Reference, Que
7. C Step By Step, Michel Waite etc, Howard Sams & Company