ANSI C Programming Reference PDF
ANSI C Programming Reference PDF
1
ANSI C Programming Reference Chapter 0:
Table of Contents
1. C KEYWORD OVERVIEW ........................................................................................................................5
2
ANSI C Programming Reference Chapter 0:
12. ARRAYS................................................................................................................................................31
12.1. int and float arrays 31
12.2. Two dimensional int and float arrays. 32
12.3. char arrays. 32
12.4. Two dimensional char arrays. 33
3
ANSI C Programming Reference Chapter 0:
4
ANSI C Programming Reference Chapter 1:
1. C Keyword Overview
The following list shows all the ANSI defined C keywords. I have included sizeof because it looks like a keyword.
Keyword Chapter Section Page
auto Storage Class Keyword 6.1 19
break Flow Control Keywords 3.1 10
case Flow Control Keywords 3.2 10
char Data Type Keywords 2.5 6
const Data Type Keywords 2.9 8
continue Flow Control Keywords 3.3 11
default Flow Control Keywords 3.2 10
do Loop Control Keywords 4.2 14
double Data Type Keywords 2.4 6
else Flow Control Keywords 3.4 11
enum Data Type Keywords 2.8 7
extern Storage Class Keyword 6.4 20
float Data Type Keywords 2.3 6
for Loop Control Keywords 4.3 14
goto Flow Control Keywords 3.5 12
if Flow Control Keywords 3.4 11
int Data Type Keywords 2.2 6
long Data Type Keywords - Modifiers 2.6 6
register Storage Class Keyword 6.2 19
return Flow Control Keywords 3.6 13
short Data Type Keywords - Modifiers 2.6 6
signed Data Type Keywords - Modifiers 2.6 6
sizeof Data Type Keywords 2.13 9
static Storage Class Keyword 6.3 19
struct The STRUCT Keyword 5 16
switch Flow Control Keywords 3.2 10
typedef Storage Class Keyword 6.5 20
union Storage Class Keyword 6.6 20
unsigned Data Type Keywords - Modifiers 2.6 6
void Data Type Keywords 2.7 7
volatile Data Type Keywords 2.10 8
while Loop Control Keywords 4.4 16
5
ANSI C Programming Reference Chapter 2:
Please note that there is not a boolean data type. C does not have the traditional view about logical comparison, but
thats another story.
The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in
stone. ANSI has the following rules:
What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int'
should be less bytes than a 'long int'.What this means in the real world is:
6
ANSI C Programming Reference Chapter 2:
Note:
• If a variable is defined with enum it is considered by the compiler to be an integer, and can have ANY integer
value assigned to it, it is not restericted to the values in the enum statement.
See Also:
#define preprocessor.
Example:
/* This program will compile but the #define statement
* will cause FALSE and TRUE to have a value of 1*/
#define FALSE 1
main()
{
enum Boolean_t Boolean;
7
ANSI C Programming Reference Chapter 2:
}
/*************** Resulting printout: ******************/
False has a value of 1
True has a value of 1
Examples
1) /* Base address of the data input latch */
lsb = *handle->baseAddr;
middle = *handle->baseAddr;
msb = *handle->baseAddr;
Between reads the bytes are changed in the latch.Without the volatile, the compiler optimises this to a single
assignment:
lsb = middle = msb = *handle->baseAddr;
2)
A volatile variable is for dynamic use. E.G. for data that is to be passed to an I/O port Here is an example.
#define TTYPORT 0x17755U
See also:
Data type conversion - Storage classes. - cast - typedef keyword.
8
ANSI C Programming Reference Chapter 3:
main()
{
int var1;
float var2;
var2 = (float)var1;
}
As it happens this example would never be used in practice because C would perform the conversion automatically.
What this example does show is the cast operator () . This states, the result of the expression (in this case var1) is to
be a data type of float.
See Also
typedef keyword.
/**** Purpose: Find out the size of the different data objects ****/
#include <stdio.h>
main()
{
char array[10];
struct s {
int a;
float b;
} structure;
.....
printf(" array is %i\n", sizeof array);
printf(" struct is %i\n", sizeof structure);
}
/**************** Resulting printout ************************
array is 10
struct is 8
See also:
The strlen function Other operators malloc function.
9
ANSI C Programming Reference Chapter 3:
values. The branch corresponding to the value that the expression matches is taken during execution.
The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc.
Float and double are not allowed. The syntax is :
switch( expression )
{
case constant-expression1: statements1;
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}
The case statements and the default statement can occur in any order in the switch statement. The default clause is
an optional clause that is matched if none of the constants in the case statements can be matched. Consider the next
example:
switch( Grade )
{
case 'A' : printf( "Excellent" );
case 'B' : printf( "Good" );
case 'C' : printf( "OK" );
case 'D' : printf( "Mmmmm...." );
case 'F' : printf( "You must do better than this" );
default : printf( "What is your grade anyway?" );
}
Here, if the Grade is 'A' then the output will be:
Excellent
Good
OK
Mmmmm....
You must do better than this
What is your grade anyway?
This is because, in the 'C' switch statement, execution continues on into the next case clause if it is not explicitly
specified that the execution should exit the switch statement. The correct statement would be:
switch( Grade )
{
case 'A' : printf( "Excellent" );
break;
main()
{
char data[80]; /* Record read from the file. */
FILE *ptr; /* Pointer to the file. FILE is a
structure defined in <stdio.h> */
10
ANSI C Programming Reference Chapter 3:
if( expression1 )
statement1;
else if( expression2 )
statement2;
else if( expression3 )
statement3;
.....
else
statementN;
11
ANSI C Programming Reference Chapter 3:
goto lab1;
lab1:
goto allows the program to 'jump' to a named label, in this case lab1, the target label MUST be terminated with a :
(colon).
Example.
/* A division checking for divide by zero demonstrates the goto statement.*/
#include <stdlib.h>
main()
{
char data[100];
double num1, num2;
end_prog:
printf(" Program ended\n");
}
int func(void);
main()
{
printf("%d \n", func());
}
int func(void)
{
return 7;
}
What ever follows the return statement will be evaluated as an expression. So, to be consistant you should place
brackets around the return value.
return(7);
Finally, if the function returns a void the return statement is not required, but maybe needed to leave a function
before the end of the function block. Here is an example.
void CheckDate(int)
main()
12
ANSI C Programming Reference Chapter 4:
{
CheckDate(40)
}
main()
{
int num;
puts ("This program will return the factorial of a number.");
printf("Please enter the number ==> " );
scanf("%d", &num);
printf(" %d! is %d\n",num, factorial(num) );
}
13
ANSI C Programming Reference Chapter 4:
do
{
printf(" i is %d\n", i);
}
while(--i);
}
The program result will look like this:
i is 5
i is 4
i is 3
i is 2
i is 1
The main difference between do and while is the time that expression is evaluated.
• do performs the first test AFTER the first iteration. 'do...while' works like 'repeat ...until' in Pascal.
• while performs the first test BEFORE the first iteration.
Basic principles
Say you wanted to print all the numbers between 1 and 5, you could write:
main()
{
int count=1;
printf("%d\n", count++);
printf("%d\n", count++);
printf("%d\n", count++);
printf("%d\n", count++);
printf("%d\n", count++);
}
As you can see this program would NOT be very practical if we wanted 500 numbers. The problem can be solved
with the for statement as below.
main()
{
int count;
More detail
The for statement performs the following actions while looping.
14
ANSI C Programming Reference Chapter 4:
for (expression_1 ; expression_2 ; expression_3) statement ;
1. Execute expression_1.
2. Evaluate expression_2, AND, if TRUE proceed; if FALSE exit the loop.
3. Execute statement.
4. Execute expression_3.
5. Repeat step 2.
Any of the three expressions can be missing; if the first or third is missing, it is ignored.
If expression_2 is missing, it is assumed to be TRUE.
Note, however, that both semicolons (;) are required. Also, be aware that statement may NEVER be executed
as it is possible expression_2 will be FALSE the first time it is evaluated.
expression_1;
while (expression_2)
{
statement(s);
expression_3;
}
The following example is an infinite loop:
main()
{
for( ; ; ) puts(" Linux rules!");
}
while(--i)
{
printf(" i is %d\n", i);
}
}
The expression i-- is evaluated and if its true the statements in the block are executed. The loop continues until the
expression is false (zero). The result will look like this:
i is 4
i is 3
i is 2
i is 1
It is important to note that the statements on a while will not get executed if the first evaluation of the expression is
FALSE. If you do not want this to happen you may prefer to use the do statement. Now consider the next example:
main()
{
int i=5;
while(--i);
{
printf(" i is %d\n", i);
}
}
The result will look like this:
i is 0
This is because of the ; at the end of the while statement which means the while will loop (executing NULL
statements) until i is zero. Execution will then continue down the program (to the printf).
15
ANSI C Programming Reference Chapter 5:
See also:
break keyword - continue keyword.
Jo Loss Maths A
Harry Carpenter English A
Billy King Maths C
struct {
char cname[8];
char sname[16];
char exam[16];
char grade;
} record;
The statement above declare a variable called record with 4 members called cname, sname, exam, grade. The
structure as a whole can be referred to as record and a member can be referenced as record.exam. Structures can be
declared in various forms...
struct x {int a; int b; int c;}; /* declaration */
struct {int a; int b; int c;} z;
struct x z;
All the examples above are structure declarations,
• The first gives x as a 'structure tag' - this is optional.
• The first and second declare the members of the structure.
• Second and third give z this is the variable that assumes thestructure type.
main()
{
struct x z;
z.a = 10;
z.b = 20;
z.c = 30;
}
And to retrieve a value from a structure member:
struct x {int a; int b; int c;} ;
main()
{
struct x z;
z.a = 10;
z.a++;
printf(" first member is %d \n", z.a);
}
16
ANSI C Programming Reference Chapter 5:
• If the structure is large it is more efficient to pass a pointer to the structure instead of the structure its self. This
technic is also used to pass pointers to arrays between functions.
• When passing a structure to a function, you actually pass a COPY of the structure. Therefore it is not possible to
change the values of members within the structure as the copy is destroyed when the function ends.
So how does it all work? Here is an example.
struct x {int a; int b; int c;} ; | struct x {int a; int b; int c;} ;
void function(struct x); | void function(struct x *);
|
main() | main()
{ | {
struct x z; | struct x z, *pz; /* 3 */
| pz = &z; /* 4 */
z.a = 10; /* 1 */ | z.a = 10;
z.a++; | z.a++;
|
function(z); /* 2 */ | function(pz); /* 5 */
} | }
void function( struct x z) | void function(struct x * pz)
{ | { /* 6 */
printf(" first member %d \n", z.a); | printf(" first member %d \n", (*pz).a);
} | }
Here is the annotation.
1. Give a structure member a value.
2. Pass a COPY of the whole structure to the function.
3. Define 'pz' a pointer to a structure of type 'x'.
4. Put the address of 'z' into 'pz'. 'pz' now POINTS to 'z'. PLEASE NOTE. 'z' is defined to reserve memory equal to
the size of the structure. 'pz' only holds an address so will be 4 bytes long.
5. Pass the pointer into the function.
6. Print the value of the member 'a'.
The (*pz).a syntax is used a great deal in C and it was decided to create ashort hand for it. So:
(*pz).a == pz->a
main()
{
/* Declare two variables: *z == type struct x
and * pz == a pointer to type struct x */
struct x z, *pz;
17
ANSI C Programming Reference Chapter 6:
void function(struct x * pz)
{
/* Print the value of 'z.a' by referencing the pointer 'pz'
which holds the address of 'z' */
printf(" first member inside the function %d \n", pz->a);
See Also:
typedef keyword. - Linked lists.
{
printf("%d\n", Road);
}
static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will
not be seen by the object modules that are brought in.
'static' can also be defined within a function! If this is done the variable is initalised at run time but is not reinitalized
when the function is called. This is serious stuff - tread with care.
{
static Count=1;
}
There is one very important use for 'static'. Consider this bit of code.
char * func(void);
18
ANSI C Programming Reference Chapter 6:
main()
{
char *Text1;
Text1 = func();
}
char * func(void)
{
char Text2[10]="martin";
return(Text2);
}
Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and
will disappear when we exit the function and could be overwritten by something else. The answer is to specify
static char Text[10]="martin";
The storage assigned to 'text2' will thus remain reserved for the duration if the program.
Source 1 | Source 2
-------- | --------
extern int count; | int count=5;
|
write() | main()
{ | {
printf("count is %d\n", count); | write();
} | }
Count in 'source 1' will have a value of 5. If source 1 changes the value of count - source 2 will see the new value.
main ()
{
Boolean flag = TRUE;
}
And as a final example, how about creating a string datatype?
typedef char * String;
main()
{
String Text = "Thunderbird";
printf("%s\n", Text);
}
The main use for typedef seems to be when defining structures. For example:
typedef struct {int age; char *name} person;
person people;
Take care to note that person is now a type specifier and NOT a variable name.
I would expect to see 'typedef' in header files.
19
ANSI C Programming Reference Chapter 7:
By default the first variable (a) is initalised. To assign a value to a variable you can say:
union_var.b=99.99;
union_var.a=34;
union_var.c='x';
It's important to note that the storage will only hold ONE value, looking at the three lines above, union_var.a
overwrites union_var.b and then union_var.c overwrites union_var.a
I have yet to see more than one use for this keyword.
See Also:
Data types.
• assignment
=
• selection (branching)
if (expression)
else
switch
• iteration (looping)
while (expression)
(expression;expression;expression)
do {block}
7.2. Blocks
These statements are grouped into blocks, a block is identified by curly brackets.There are two types of block.
• statement blocks
if ( i == j)
{
printf("martin \n");
}
• The statement block containing the printf is only executed if the i == j expression evaluates to TRUE.
• function blocks
int add( int a, int b) /* Function definition */
{
int c;
c = a + b;
return c;
}
• The statements in this block will only be executed if the add function is called.
20
ANSI C Programming Reference Chapter 7:
7.3. Comments.
Lets start with a few examples.
main()
{
int Counter=0; /* Initalise Counter */
/* a comment */
/*
* Another comment
*/
/*****************
*
* Final comment.
*
*****************/
}
A comment starts with a /* and ends with */. Comments started in this way can span multiple lines but cannot be
nested !! For example:
main()
{
int Count = 0; /* Initalise
* Counter to 0 */
/* /* Invalid comment */ */
}
This will give a syntax error, since comments within comments are illegal.
Note:
• Preprocessors should start in column 1.
21
ANSI C Programming Reference Chapter 7:
7.5. Macros
Macros are built on the #define preprocessor.
Normally a #define would look like:
#define PI 3.142
The main difference is that the first example is a constant and the second is an expression. If the macro above was
used in some code it may look like this:
#define SQUARE(x) x*x
main()
{
int value=3;
printf("%d \n", SQUARE(value));
}
After preprocessing the code would become:
main()
{
int value=3;
printf("%d \n", value*value);
}
Notes:
• The value passed to SQUARE could have been an int float or double
• Long macros can span multiple lines by using a followed by a newline (return).
22
ANSI C Programming Reference Chapter 8:
In this example i is a global variable, it can be seen and modified by main and any other functions that may
reference it.
int i=4;
main()
{
i++;
}
func()
{
int i=10; /* Internal declaration */
i++; /* Internal variable */
}
i in main is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control
returns to main the internal variable will die and and any reference to i will be to the global.
See Also:
See Storage classes to see the more powerful features of variable declarations.
8.2. Declaration.
Just like variables, all functions have to be declared before use. Here is an example.
int add( int, int);
This statement declares a function called add, it has two integer arguments and returns an integer.
8.3. Definition.
The definition is the meat of the function. Here's an example.
main()
{
23
ANSI C Programming Reference Chapter 8:
int i=1;
printf("i starts out life as %d.", i);
i = add(1, 1); /* Function call */
main()
{
int i=4; /* variable declaration */
int* ptr; /* int pointer */
ptr = &i; /* 'ptr' now contains the address of 'i'*/
main()
{
int i[I_SIZE]={4,6}; /* array declaration */
int count=0;
for (count=0;count<I_SIZE;count++)
printf("i starts out life as %d.\n", i[count]);
24
ANSI C Programming Reference Chapter 9:
++*ptr; /* Add 1 to the first element in the array */
++*(ptr+1); /* And the second element */
return;
}
main()
{
char array1[10]="987654321"; /* one less so the \0 will fit */
function1(char * array)
{
printf("%s\n", array); /* printf expects a pointer. */
9.1. Arithmetic
+
-
/
*
% modulo
-- Decrement (post and pre)
++ Increment (post and pre)
25
ANSI C Programming Reference Chapter 9:
9.2. Assignment
These all perform an arithmetic operation on the lvalue and assign the result to the lvalue. So what does this mean in
English? Here is an example:
counter = counter + 1;
can be reduced to
counter += 1;
Here is the full set.
=
*= Multiply
/= Divide.
%= Modulus.
+= add.
-= Subtract.
<<= left shift.
>>= Right shift.
&= Bitwise AND.
^= bitwise exclusive OR (XOR).
|= bitwise inclusive OR.
9.3. Logical/Relational
== Equal to
!= Not equal to
>
<
>=
<=
&& Logical AND
|| Logical OR
! Logical NOT
9.4. Bitwise
& AND (Binary operator)
| inclusive OR
^ exclusive OR
<< shift left
>> shift right
~ one's complement
26
ANSI C Programming Reference Chapter 9:
• The third expression assigns a value of 1 to i. 1 is considered to be true because it is non-zero.
• The fourth expression assigns a value of 0 to i. 0 is considered to be false.
• The fith expression assigns a value of 2 to i. 2 is considered to be true, because it is non-zero.
9.8. Idioms
Here are some C idioms that may be useful.
• Place \0 at the location pointed to by ptr then increment ptr
*ptr++ = '\0';
• Increment ptr then place \0 at the location pointed to by ptr
*++ptr = '\0';
• This program will print itself! I guess it's not of any real use, but I think its clever.
main(a) {a="main(a) {a=%c%s%c;printf(a,34,a,34);}"; printf(a,34,a,34);}
^
|
9.9. Operator Precedence
&&
The following tables show the order in which operators
||
are evaluated. Please note the following.
?:
• The order in which the operands are evaluated is not
specified in the ANSII standard. = += -= *= /= %= &= ^= |= <<= >>=
• For readability you should not rely on these rules! ,
Put everything in brackets so you intension is clear
to the compiler and other programmers.
Summary precedence
table.
All operators on the same line have the same
precedence. The first line has the highest precedence.
() [] -> .
! ~ ++ -- + - * & sizeof
* / %
+ -
<< >>
< <= >= >
== !=
&
27
ANSI C Programming Reference Chapter 10:
<= Less than or equal to.
Detailed precedence >= Greater than or equal to.
table == Equal to.
All operators in the same block have the same prece- != Not equal to.
dence. The first block has the highest precedence. More Bitwise & bitwise AND
Group Operator Description ^ bitwise Excusive OR
Membership. () Function call. | bitwise OR
[] Array. Logical. && Logical AND
-> Structure pointer.
Logical. || Logical OR
. Structure member.
Conditional ?: Conditional construct.
Unary. ! Logical NOT
Assignment = Equals
~
+= assignment
++ Increment.
-= assignment
-- Decrement.
*= assignment
+
/= assignment
-
%= assignment
* Pointer to data
&= assignment
& Address of a variable.
^= assignment
sizeof
(type) type cast. |= assignment
<<= assignment
Binary * Multiply.
>>= assignment
/ Divide.
% Modulo. Series , Comma
Binary + Addition
- Subtraction.
Bitwise << Shift left.
>> Shift Right.
Relational < Less than.
> Greater than.
AND & will copy a bit to the result if it exists in both operands.
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
unsigned int c = 0;
1
ANSI C Programming Reference Chapter 11:
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
unsigned int c = 0;
c = a | b; /* 61 = 0011 1101 */
}
XOR ^ copies the bit if it is set in one operand (but not both).
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
unsigned int c = 0;
c = a ^ b; /* 49 = 0011 0001 */
}
main()
{
unsigned int Value=4; /* 4 = 0000 0100 */
Usually, the resulting 'empty' bit is assigned ZERO.Please use unsigned variables with these operators to avoid
unpredictable results.
11. Constants
Be sure you understand the difference between a 'constant' and a declaration. A constant has a value that cannot be
changed. For example:
1234
'x'
9.89
"String"
Constants are used to assign a value to a variable, e.g.
int i; /* declare a variable called 'i' */
i=1234; /* assign the constant value 1234 to
* the variable 'i' */
i++; /* Change the value of the variable. */
30
ANSI C Programming Reference Chapter 12:
0xff (Hexidecimal)
0100 (Octal)
'\xf' (Hex character)
Examples of their use are:
int i=255; /* i assigned the decimal value of 255 */
i-=0xff /* subtract 255 from i*/
i+=010 /* Add Octal 10 (decimal 8) */
See also:
#define - Strings
12. Arrays.
Arrays can be created from any of the C data types int, float, char. I start with int and float as these are the easiest to
understand. Then move onto int and float multi dimentional arrays and finally char arrays
31
ANSI C Programming Reference Chapter 12:
The syntax for an array is:
main()
{
int count[5]; /* interger 5 element array */
float miles[10]; /* floating point 10 element array */
}
Now, the important fact is that the elements start at 0 (ZERO), so, 'count' above has elements 0, 1, 2, 3, 4.
To change the value of the 5th element we would code:
main()
{
int count[5];
count[4] = 20; /* index 4 is the 5th element */
}
If we want to initalise 'count' at definition we can say:
main()
{
int i;
int count[5]={10, 20, 30};
for (i=0; i< 5; i++)
{
printf("%d ", count[i]);
}
puts("")
}
The result will be:
10 20 30 0 0
We can see from the example above that the elements that have NOT been initalised have been set to zero.
One last thing to show you. If all the elements are being initialized when the variable is being declared, the compiler
can work out the number of elements for you. So this example will create an array with 3 elements.
main()
{
int i;
int count[]={10, 20, 30};
}
Don't forget all the stuff so far also applies to float.
32
ANSI C Programming Reference Chapter 13:
main()
{
char letter='x';
char letters[10]='f','a','x',' ','m','o','d','e','m','\0';
char text[10]="fax modem";
}
Note that the double quotes mean 'text string', so they will add the NULL automatically. This is the only time that
text can be loaded into an array in this way. If you want to change the contents of the array you should use the
function strcpy.
13. Pointers.
Pointers are at the heart of C. When you crack this subject, you have got the worst of C behind you. Before you
tackle pointers though, you should get a grip on arrays.
• First principles.
• Definition of a pointer.
• Pointers to strings.
• Pointers to arrays.
• Char arrays verses char pointers.
• Void pointers.
• Pointers to pointers.
• Pointers to functions.
• Linked lists.
33
ANSI C Programming Reference Chapter 13:
main()
{
int Length;
Length = 20;
}
the decimal value 20 (Hex 14) is placed into the storage location.
(Address) (Data)
F1 <- ------ Length
F2
F3
F4 14
Finally, the program is expanded to become:
main()
{
int Length;
Length = 20;
printf("Length is %d\n", Length);
printf("Address of Length is %p\n", &Length);
}
The output would look something like this .....
Length is 20
Address of Length is 0xF1
Please note the '&Length' on the second printf statement. The & means address of Length. If you are happy with
this, you should push onto the pointers below.
So far, this variable looks the same as above, the value stored at 'Width' is unknown. To place a value in 'Width' you
could code.
main()
{
int *Width;
*Width = 34;
}
(Address) (Data)
F1 00<- ------- Width
F2 00 (Data) (Address)
F3 00 *Width ---------- ->00 D1
F4 14 ------ 00 D2
00 D3
22 D4
Unlike the Length = 20 example above, the storage pointed to by 'Width' does NOT contain 34 (22 in Hex), it
contains the address where the value 34 can be found. The final program is...
main()
{
char *Width;
34
ANSI C Programming Reference Chapter 13:
*Width = 34;
A pointer can point to any data type, ie int, float, char. When defining a pointer you place an * (asterisk) character
between the data type and the variable name, here are a few examples.
main()
{
int count; /* an integer variable */
int *pcount; /* a pointer to an integer variable */
float miles; /* a floating point variable. */
float *m; /* a pointer */
char ans; /* character variable */
char *charpointer; /* pointer to a character variable */
}
main() main()
{ {
char colour[]="red"; char *colour="red";
printf("%s \n",colour); printf("%s \n",colour);
} }
The answer is, not a great deal, at first sight! They both print the word red because in both cases 'printf' is being
passed a pointer to a string. The difference is on how the pointer is defined.
35
ANSI C Programming Reference Chapter 13:
main()
{
fpointer = func1; /* Put the address of 'func1' in 'fpointer' */
fpointer(); /* Execute 'func1' */
fpointer = func2; /* Repeat for 'func2' */
fpointer();
}
int func1(void)
{
puts("martin was ere");
}
int func2(void)
{
puts("alex was ere");
}
36
ANSI C Programming Reference Chapter 14:
1. The arrary will hold all the data in character format. It
would be nice to hold the integer and decimal numbers in
a more appropriate form. Name Age Pointer
2. If you have more than 50 records the program has to be
altered and recompiled.
The first problem could be fixed by defining an
↓
array of structures BUT both problems can be solved with Name Age Pointer
linked lists.
The concept of a linked list is fairly simple. It is a group of
structures linked together by pointers, as shown in the figure
↓
to the right. NULL
The "Name Age Pointer" block could be defined as below:
struct record {char name[20]; int age; struct record *next_rec;};
The important bit is "struct record *next_rec" this is the pointer to the next structure (record). It will either point to
the next record which will require memory reserved with the malloc function or NULL if its the last record.
See Also:
VOID keyword. - function arguments - Strings - Arrays.
Example:
Library: stdlib.h
Prototype: void *malloc(size_t size);
Syntax: char * String;
C++ equivalents
new is the C++ equivalent to malloc.
delete is the C++ equivalent to free.
37
ANSI C Programming Reference Chapter 14:
Please note the 00 at the end of Thunder. This is the NULL character and is used to mark the end of a string.
If we wanted to O/P the data pointed to by a char pointer we can code.
Source:
main()
{
char *Text1 = "Thunder"; /* Define and initalize */
char *Text2; /* Define only */
I. Except for %% and %n, all the identifiers expect to extract an argument from the printf parameter list.
II. All of the parmameters should be the value to be inserted. EXCEPT %s, this expects a pointer to be passed.
38
ANSI C Programming Reference Chapter 14:
Example.
main()
{
int number=5;
char *pointer="little";
printf("Here is a number %d and a %s word.\n", number, pointer);
}
/*********************************
* Program result is: */
Here is a number 5 and a little word.
Field width.
By default the width of a field will be the minimum required to hold the data. In the example above the width of %s
becomes 6. If you want to control the field width you can use the following syntax.
main()
{
int number=5;
char *pointer="little";
Flags
The format identifers can be altered from their default function by applying the following flags:
- Left justify.
0 Field is padded with 0's instead of blanks.
+ Sign of number always O/P.
blank Positive values begin with a blank.
# Various uses:
%#o (Octal) 0 prefix inserted.
%#x (Hex) 0x prefix added to non-zero values.
%#X (Hex) 0X prefix added to non-zero values.
%#e Always show the decimal point.
%#E Always show the decimal point.
%#f Always show the decimal point.
%#g Always show the decimal point, trailing zeros not removed.
%#G Always show the decimal point, trailing zeros not removed.
I. The flags are placed between the % and the field width or format identifier.
II. Where it make sense, more than one flag can be used.
Here are a few more examples.
printf(" %-10d \n", number);
printf(" %010d \n", number);
printf(" %-#10x \n", number);
printf(" %#x \n", number);
39
ANSI C Programming Reference Chapter 15:
\xhh Hex number
\ Preprocessor line continuation, must be immediately followed by \n.
These can be used anywhere that C expects to see a character constant. Must be time for a quick example.
main()
{
char word[]="\x6d\x6f\x64\x65\x6d";
printf("%s\n", word);
}
Can you work out what will appear if you run this program??
00 01 02 03 04 05 06 07
08 09 0A 0B 0C 0D 0E 0F
10 11 12 13 14 15 16 17
18 19 1A 1B 1C 1D 1E 1F
20 21 ! 22 " 23 # 24 $ 25 % 26 & 27 '
28 ( 29 ) 2A * 2B + 2C , 2D - 2E . 2F /
30 0 31 1 32 2 33 3 34 4 35 5 36 6 37 7
38 8 39 9 3A : 3B ; 3C C 3D = 3E > 3F ?
40 @ 41 A 42 B 43 C 44 D 45 E 46 F 47 G
48 H 49 I 4A J 4B K 4C L 4D M 4E N 4F O
50 P 51 Q 52 R 53 S 54 T 55 U 56 V 57 W
58 X 59 Y 5A Z 5B [ 5C \ 5D ] 5E ^ 5F _
60 ` 61 a 62 b 63 c 64 d 65 e 66 f 67 g
68 h 69 i 6A j 6B k 6C l 6D m 6E n 6F o
70 p 71 q 72 r 73 s 74 t 75 u 76 v 77 w
78 x 79 y 7A z 7B { 7C | 7D } 7E ~ 7F
15.2. ctype.h
isalnum Checks whether a character is alphanumeric (A-Z, a-z, 0-9)
isalpha
iscntrl Checks whether a character is a control character or delete ( decimal 0-31 and 127)
isdigit Checks whether a character is a digit (0-9)
isgraph Checks whether a character is a printable character, excluding the space (decimal 32)
islower Checks whether a character is a lower case letter (a-z).
isprint Checks whether a character is printable (decimal 32-126).
ispunct Checks whether a character is punctuation (decimal 32-47, 58-63, 91-96, 123-126)
isspace Checks whether a character is white space - space, CR HT VT NL, FF.
isupper Checks whether a character is an upper case letter (A-Z).
isxdigit Checks whether a character is hex digit (0-9, A-F, a-f).
toupper Converts a lowercase character to uppercase. int toupper(int c)
tolower Convert an uppercase character to lowercase. int tolower(int c)
40
ANSI C Programming Reference Chapter 15:
15.3. math.h
acos asin atan atan2 cos sin tan cosh sinh tanh exp frexp ldexp log log10 modf pow sqrt ceil fabs
floor fmod
Note! For some reason abs is in stdlib.h
15.4. stdio.h
This header defines all the ANSI I/O functions that allow you to read and write to files and devices. Low level (non
ANSI) functions are also available.
rename remove tmpfile tmpnam fflush freopen setbuf setvbuf fscanf vfprintf vprintf vsprintf scanf
ungetc fread fwrite fgetpos fseek fsetpos ftell rewind clearerr fseek
15.5. stdlib.h
abort abs atexit atof atol calloc div exit labs ldiv mblen mbstowcs mbtowc realloc strtod strtoul
wctomb wcstombs
atoi Accepts +-0123456789 leading blanks and converts to integer.
bsearch Binary chop.
getenv Get an environmental variable.
free memory allocated with malloc.
malloc dynamically allocate memory.
qsort Sort an array.
rand Generate a random number.
strtol String to long integer conversion. Takes data in various number bases.
srand Seed a random number.
system Issue a command to the operating system
15.6. string.h
memchr memcmp memcpy memmove memset strcoll strcspn strerror strlen strncat strncmp strpbrk
strspn strxfrm
strcpy Copy strings.
strcat Concatinate two strings.
strchr Search for a character in a string.
strcmp Compare strings.
strncpy Copy part of a string.
strrchr Search for a character in a string.
41
ANSI C Programming Reference Chapter 16:
strstr Search a string for a substring.
strtok The books say this function splits a string into tokens. I think its function is best described as parsing a string.
15.7. time.h
asctime clock ctime difftime gmtime localtime mktime strftime time
They have been tested on a PC running Linux and using the 'gcc' compiler. You can extract the programs with the
'save' option under 'file' and compile with your own compiler.
42
ANSI C Programming Reference Chapter 17:
43
ANSI C Programming Reference Chapter 17:
Identifier. The names used to refer to stored data values such as constants, variables or functions.
Integer. A number without a fractional part.
Keyword. A word which has a predefined meaning to a 'C' compiler and therefore must not be used for any
other purpose.
library file. The file which contains compiled versions of commonly used functions which can be linked to an
object file to make an executable program.
Library function. A function whose code is contained in the external library file.
Line. One line of input from the standard input device (keyboard) which is terminated with a newline
character. The newline character is replaced by a null character.
Literal. Characters, letters or strings which are to be taken literally and used as constants rather than
identifiers.
Object C++ term, not used in ANSI C.
Object Code. Code which is directly understandable by the machine (machine code).
Operand. An expression acted on by an operator. For example:
z = a + b;
a and b are both operands of the + operator.
Parameter. A value received by a function.
Pointer. Variable containing an address.
Polymorphism C++ term, not used in ANSI C.
Precedence (of operators) The order in which operators are dealt with during the evaluation of an expression.
Preprocessor. A processor which manipulates the initial directives of the source file which contains instructions
about how the source file shall be processed and compiled.
Preprocessor directive. Source file instruction about how the file shall be processed and compiled.
Program. A text file comprising code which can be compiled.
Run time error. An error which occurs when a program is executed.
Reserved word Same as keyword. A word which has a predefined meaning to a 'C' compiler and therefore must not
be used for any other purpose.
Scope.
Source code. A text file comprising code which can be compiled.
Statement. A simple statement is an expression followed by a semicolon. (See compound statement and block).
String. A string in 'C' is an array of characters terminated by a Null character ('\0').
Syntax error. A mistake in the source code which prevents the compiler from converting it into object code.
Variable. An identifier (and storage) for a data type and for which the data value is allowed to change as the
program runs.
44