A Crash Course in C
A Crash Course in C
copyright Anand Mehta
January 1995
A Crash Course in C 1
A Crash Course in C i
Contents
0 Intro duction 1
1 Fundamentals 2
1.1 Example programs : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 2
1.2 Variables : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 3
1.3 Input/Output : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 4
1.4 Keywords and Op erators: The C Language : : : : : : : : : : : : : : : : : : : : : : : 5
1.5 Expressions and Statements : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 9
1.6 Control Flow : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 9
1.7 The C Prepro cessor : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 13
1.8 Problems : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 14
2 Functions 18
2.1 Reasons for Using Functions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 18
2.2 Basic Structure : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 18
2.3 Return Statement : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 20
2.4 Di erence b etween ANSI-C and \Traditional C" : : : : : : : : : : : : : : : : : : : : 21
2.5 Ob ject Storage Classes and Scop e : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 22
2.6 Larger Programs : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 24
2.7 Macros : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 27
2.8 Problems : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 27
3 Pointers 29
3.1 Pointer De nition and Use : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 29
3.2 Pointers as Function Arguments: \Call byValue" : : : : : : : : : : : : : : : : : : : : 31
3.3 Arrays : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 32
3.4 Functions Returning Pointers : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 34
3.5 Multidimensional Arrays : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 36
3.6 Strings : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 41
3.7 Command Line Arguments : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 41
3.8 Pointers to Functions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 42
ii A Crash Course in C
3.9 Problems : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 42
4 Structures 43
4.1 Syntax and Op erations : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 43
4.2 typedef : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 45
4.3 Array of Structures : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 45
4.4 Use with Functions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 46
4.5 Linked Lists : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 48
4.6 union : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 49
4.7 enum : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 50
4.8 Example: Complex Numb ers : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 52
4.9 Problems : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 54
5 C Libraries 55
5.1 Memory Allo cation : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 55
5.2 Math Libraries : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 56
5.3 Random Variables : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 57
5.4 Input/Output : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 58
5.5 Strings : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 60
A Make Program 61
B C Style Guide 63
B.1 General Style : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 63
B.2 Layout : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 66
B.3 Co ding Practice : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 66
B.4 Naming Conventions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 67
C Answers to Problems 68
x0 A Crash Course in C 1
0 Intro duction
Reasons to use C:
p ointers and structures
encourages well structured control ow
mo dular programming is encouraged
easy to learn C has few keywords
p ortability to di erent machines
many functions are in libraries, not intrinsic parts of the language
lexical scoping for variables
References:
Brian Kernighan and Dennis Ritchie, The CProgramming Language 2nd edition K&R
Stephen G. Ko chan, Programming in C, Programming in ANSI C Ko chan
Al Kelley and Ira Pohl, ABook on C
American National Standard for Information Systems|Programming Language C, X3.159-
1989.
Three steps are necessary to use C:
write the program using an editor
compile and link it; on Unix systems, use
cc program.c
cc -o
This automatically runs three separate pro cesses, using the source les
the output:
{ prepro cessor
{ compiler
{ linker
If there are no errors, this pro duces an executable le. The rst cc command pro duces the
le a.out, while the second makes the le
execute the program
Di erent systems have di erent pro cedures to use C. See the manual or help les for details.
2 A Crash Course in C x 1.1
1 Fundamentals
1.1 Example programs
The following are simple examples to get things started. They do not do anything useful, but they
illustrate some key characteristics of C.
/* this is a comment */
main /* function definition */
{ /* start of block */
printf"Hello world\n"; /* output; statement ends with a semicolon */
/* use '\n' in printf to get a linefeed */
} /* end of block */
Things to note in example programs:
comments cannot b e nested.
main is the function where the program b egins execution, and can only o ccur once.
C is case sp eci c.
all white space spaces, tabs, blank lines, comments is equivalent to one space.
Syntax:
main
f
variable declarations
statements
g
main
{
int x; /* declaration and definition */
x=5; /* assignment */
printf"d\n", x; /* output x as an integer */
}
main
{
int x=17, y=12, z; /* declaration, definition, and initialization */
z = x + y; /* arithmetic expression */
printf"z = d + d = d\n", x, y, z; /* each d prints one integer */
printf"d * d = d\n", x, y, x*y;
}
main
{
int x;
scanf"d", &x; /* values input from the keyboard using scanf: */
printf"x = d\n", x; /* and a pointer to x */
}
A common error when using scanf is not giving p ointers as the arguments; to input a variable, use
int x;
scanf"d", &x; /* correct */
NOT
int x;
scanf"d", x; /* incorrect */
x1.2 A Crash Course in C 3
1.2 Variables
All variables must be declared and de ned b efore they can be used. Variable names can be comp osed of
characters, digits, and the underscore character _, and can usually be up to 32 characters long. Vari-
able names should not b egin with an underscore|these names are used by the compiler and the libraries.
Variables have sp eci c typ es and usage; basic data typ es:
char: a single byte, used for one character
{ can sp ecify signed or unsigned, although signed is preferred for compatibility with int
int: integers
{ can mo dify with short or long
{ can sp ecify signed or unsigned
float: single precision oating p oint real number
double: double precision oating p ointnumber
void: no typ e value, for p ointers and functions
The sp eci c size of eachtyp e dep ends on the implementation; see
The derived data typ es are
arrays array[10]
p ointers *pointer
functions function
structures structure.member
enumerated enumerated_variable
union union_name.member
All variables must b e declared and de ned; they can also b e initialized and assigned a value.
declaration: sp eci es the typ e of the identi er
de nition: reserves storage space for the ob ject
initialization: gives an initial value to the ob ject during de nition
assignment: gets a new value
/*** definition of constants ***/
main
{
char c = 'x';
char c1 = '0'; /* the character 'zero', with the integer value for ASCII0 */
char c2 = '\0'; /* has the "integer" value zero */
int n = 10;
int n_oct = 065; /* octal */
int n_hex = 0x3d; /* hexadecimal */
long m = 10L;
unsigned int k = 304U;
unsigned long l = 3040UL;
float x1 = 143.0;
float x2 = 24.6e-3;
double y = 34.1L; }
4 A Crash Course in C x 1.3
1.3 Input/Output
Basic input/output is obtained using the standard library
Syntax:
printf"control string", variable1, variable2, :::
scanf"control string", pointer1, pointer2, :::
The control string has place holders for the variables b eing used see tables on page 16. For printf,
there can also b e characters in the control string. For scanf, the p ointers to the variables b eing inputed
must b e used. Sp ecial characters are listed on table 5 on page 16.
/** using printf and scanf **/
main
{
int x=10;
float y;
printf"1 d\n", x;
printf"2 d\n", x*5;
printf"3 x = ";
printf"d", x;
printf"\n"; /** same as 4 **/
printf"4 x = d\n", x; /** same as 3 **/
printf"input x: "; scanf"d", &x; /** prompts for input **/
printf"5 x = d\n", x;
/** can input several values of different types with one scanf command **/
printf"input x, y: "; scanf"d f", &x, &y;
printf"6 x = d, y = f\n", x, y;
}
Output: 1 10
2 50
3 x = 10
4 x = 10
input x: 40
5 x = 40
input x, y: 20 34.5
6 x = 20, y = 34.500000
x1.4 A Crash Course in C 5
Table 1: C Keywords K&R, p. 192
data type declarations control flow statements
auto float long static unsigned break do if
char enum register struct void case else return
const extern short typedef volatile continue for switch
double int signed union default goto while
1.4 Keywords and Op erators: The C Language
C has a small set of keywords; all are used to either declare data typ es or control the ow of the program.
See table 1 for a list of the keywords. The C op erators are listed in table 2 on page 15.
1.4.1 Basic Op erators
Some basic op erators are
*, /, ; +, - arithmetic op erators
{ mo dulus division remainder
<, >, <=, >=; ==, !=; &&; || logical op erators
{ the logical op erators return a 1 true or 0 false.
{ for any conditional test, any non-zero value is true, and a 0 is false.
{ == equality comparision not =
{ != not equal to
{ && || logical AND and OR op erators
{ A common error is using the assignment op erator = when the logical op erator == is required,
e.g. x = 2 instead of x == 2; b oth are valid expressions, so the compiler will not indicate
an error.
=, +=, -=, *=, /=, = assignment op erators
{ op= assignment, E1 op=E2 <==> E1=E1 op E2, with E1 evaluated once
{ for example, x+=2 ==> x=x+2
++, -- increment/decrementby 1, as a pre x or p ost x
{ pre x: increments the variable and gives the new value as the result
{ p ost x: gives the old value as the result and then increments the variable
! negation
{ !0 ==> 1
{ !any non-zero value ==> 0
? : conditional, compact if-else as an expression instead of a statement
type casts ob ject into a di erenttyp e
, combines separate expressions into one,
{ evaluates them from left to right
{ the value of the whole expression is the value of the rightmost sub-expression
6 A Crash Course in C x 1.4
/** examples of conditional operators **/
main
{
int x=0, y=10, w=20, z, T=1, F=0;
z = x == 0; /*** logical operator; result --> 0 or 1 ***/
z = x = 0; /*** assignment operator; result -->
z = x == 1;
z = x = 15;
z = x != 2;
z = x < 10;
z = x <= 50;
z = x=y < 10; /*** performs assignment, compares
z = x==5 && y<15;
z = x==5 && y>5 && w==10;
z = x==5 || y>5 && w==10;
z = T && T && F && x && x; /*** ==> F; ***/
z = F || T || x || x; /*** ==> T; ***/
/*** for && and !!, order is specified, stops when result is known, ***/
/*** value of x doesn't matter ***/
}
/** examples of the increment and decrement operators **/
main
{
int x,y;
x=5;
y = ++x; /** prefix increment **/
printf"++x: x=d, y=d\n", x, y;
x=5;
y = x++; /** postfix increment **/
printf"x++: x=d, y=d\n", x, y;
x=5;
y = --x; /** prefix decrement **/
printf"--x: x=d, y=d\n", x, y;
x=5;
y = x--; /** postfix decrement **/
printf"x--: x=d, y=d\n", x, y;
}
Output: ++x: x=6, y=6
x++: x=6, y=5
--x: x=4, y=4
x--: x=4, y=5
x1.4 A Crash Course in C 7
/** more operator examples **/
main
{
int x, y, z;
x = 128;
y = x / 10; /** y = 12, the remainder is dropped **/
y = x 10; /** y = 8, which is remainder **/
x = 10;
y = !x; /** y = 0 **/
y = !!x; /** y = 1 **/
x = 0;
y = !x; /** y = 1 **/
x = 10;
x += 2; /** x = 12 **/
x += 2; /** x = 14 **/
x = 10;
x -= 4; /** x = 6 **/
x = 10;
x *= 5; /** x = 50 **/
x = 10;
x /= 2; /** x = 5 **/
x /= 2; /** x = 2 **/
x = 2
y = x < 5 ? 5 : 10; /** y=5 **/
x = 8
y = x < 5 ? 5 : 10; /** y=10 **/
if x < 5 /** same as the conditional y = x < 5 ? 5 : 10; **/
y = 5;
else
y = 10; }
8 A Crash Course in C x 1.4
1.4.2 Order of Evaluation
Op erands of most op erators will b e evaluated in an unsp eci ed order; do not assume a particular order and
b e careful ab out side e ects of evaluations. Also, the order in which function arguments are evaluated is not
sp eci ed. There are four op erators, however, do have a sp eci ed order of op erand evaluation: && || , ?:.
/** test of order of operations **/
main
{
int x=5, y, i=4;
y = x * ++x;
printf"x = d, y = d\n", x, y;
printf"i = d, ++i = d\n", i, ++i;
}
Dep ending on the order of evaluation of the function arguments, the output can b e
Output: x = 6, y = 30
i = 4, ++i = 5
or
Output: x = 6, y = 36
i = 5, ++i = 5
These typ es of expressions should b e avoided.
1.4.3 Typ e Conversion
C do es some automatic typ e conversion if the expression typ es are mixed. If there are no unsigned values,
the rules for conversion for two op erands is
if any long double, convert other to long double
else if any double, convert other to double
else if any float, convert other to float
else
{ convert any char or short to int
{ if any long, convert other to long
If there are unsigned expressions, the conversion rules are in K&R, p. 198.
Any explicit typ e conversions can be made by casting an expression to another typ e, using double,
float, etc., b efore the expression to b e cast.
/*** truncation problem with integer divide ***/
main
{
int x=8, y=10;
float z1, z2;
z1 = x/y;
z2 = float x / float y;
printf"z1 = 6.2f, z2 = 6.2f\n", z1, z2;
}
Output: z1 = 0.00, z2 = 0.80
x1.5 A Crash Course in C 9
1.5 Expressions and Statements
Expressions include variable names, function names, array names, constants, function calls, array refer-
ences, and structure references. Applying an op erator to an expression is still an expression, and an expression
enclosed within parentheses is also an expression. An lvalue is an expression whichmay b e assigned a value,
suchasvariables.
i++ x+y z = x+y
A statement is
avalid expression followed by a semicolon
a group of statements combined into a blo ckby enclosing them in braces fg. This is then treated
as a single statement.
a sp ecial statement break, continue, do, for, goto, if, return, switch, while, and the
null statement
A statement can b e lab eled, for use with goto. Since goto disrupts structured control ow, however, it is
not generally recommended.
1.6 Control Flow
Basic control owisgoverned by the if..else, while, do...while, and for statements.
1.6.1 Decision Making
Use the if...else for conditional decisions. exp is anyvalid expression, statement is anyvalid statement
Syntax:
if exp
statement
if exp
statement
else
statement
if exp1
statement
else if exp2
statement
.
.
.
else
statement
main /*** check if a number is odd or even ***/
{
int i;
scanf"d", &i;
if i2 == 0 /** OR if !i2 **/
printf"i is even\n";
else
printf"i is odd\n"; }
10 A Crash Course in C x 1.6
/** examples of the 'if' statement **/
main
{
int x=5;
if x > 0
printf"x = d\n", x;
if x < 10
{
printf"x = d\n", x;
x += 10;
}
else
x -= 10;
if x==1
printf"one\n";
else if x==2
printf"two\n";
else if x==4
{
printf"four\n";
x /= 2;
}
else if x==5
printf"five\n";
else
{
printf"x = d\n", x;
x = 10;
}
/** 'else' matches up with last unmatched 'if' in same block level **/
if x > 0
if x 2
printf"odd\n";
else
printf"even\n";
else
printf"negative\n";
if !x 2
{
if !x 5
x /= 10;
}
else
printf"odd\n"; }
x1.6 A Crash Course in C 11
1.6.2 Lo oping
while: testing at the b eginning of the lo op
do...while: testing at the end of the lo op, after executing the lo op at least once
for: almost the same as while, in a compact form
Syntax:
while exp
statement
do
f
statement
g while exp;
for exp1-opt ; exp2-opt ; exp3-opt
statement
Here exp-opt is an optional expression.
main /*** print the numbers from 1 to 10 ***/
{
int i;
i=1;
while i<=10
{
printf"d\n", i;
i++;
}
}
main /*** print the numbers from 1 to 10 ***/
{
int i;
i=1;
do
{
printf"d\n", i++;
} while i<=10;
}
main /*** print the numbers from 1 to 10 ***/
{
int i;
for i=1 ; i<=10; i++
printf"d\n", i;
}
1.6.3 Other Control Flow
Other program control ow is governed by the switch statement, which allows comparison to a series of
constantvalues, and the goto, continue, break, and return statements.
12 A Crash Course in C x 1.6
Syntax:
switchexp
f
case const-exp:
statement-opt
break;
case const-exp:
statement-opt
statement-opt
break;
.
.
.
default:
statement-opt
break;
g
Here const-exp is a constant expression, and statement-opt is an optional statement. The break; after the
default: case is optional.
Syntax:
label: statement
goto label;
continue;
break;
return exp-opt;
Here label is a statement lab el.
The break; statement is used inside the while, do...while, for, and switch statements to automatically
drop out of the current lo op. The continue statement is used inside the lo ops not switchto jump to
the end of the lo op. With while and do...while, this jumps to the next test; with for,it jumps to the
increment step, and then the test.
/** Example with 'do...while' and 'switch': waiting for a yes/no answer **/
main
{
char ans, c;
int answer;
do
{
printf"enter y/n: "; scanf"c", &ans;
switch ans
{
case 'y': case 'Y': answer = 1; break;
case 'n': case 'N': answer = 0; break;
default: answer = -1; break;
}
} while answer == -1;
printf"answer = d\n", answer; }
x1.7 A Crash Course in C 13
1.7 The C Prepro cessor
Two essential prepro cessor commands are define and include. Constants and macros are de ned
with define. The program can b e split into separate les and combined with include, and header les
can also b e inserted. See sections 2.6 and 2.7.
include
include
include "functions.c"
define MAX 10
define TRUE 1
define FALSE 0
After inserting the math.h header le, math subroutines can b e used prop erly. To compile using the math
library on Unix, use
cc -o
/** program to calculate x using the quadratic formula **/
include
main
{
float a, b, c, d, x, x1, x2;
printf"input a, b, c: ";
scanf"f f f", &a, &b, &c;
d = b*b - 4.0*a*c;
if d >= 0 /** check if solution will be real or complex **/
{
x1 = -b+sqrtd / 2.0*a; /** sqrt from the math library **/
x2 = -b-sqrtd / 2.0*a;
/** need parentheses for proper order of operations **/
printf"x = f, f\n",x1,x2;
}
else
printf"x is complex";
}
/** an example of formated output **/
include
main
{
int n=10, i, x;
for i=0, x=1; i printf"log5d = 8.3lf\n", x, logdouble x; } 14 A Crash Course in C x 1.8 Output: log 1 = 0.000 log 2 = 0.693 log 4 = 1.386 log 8 = 2.079 log 16 = 2.773 log 32 = 3.466 log 64 = 4.159 log 128 = 4.852 log 256 = 5.545 log 512 = 6.238 The if...endif prepro cessor command can b e used to comment out a section of co de whichmayhave comments within it. /** using if for nested comments **/ define TRUE 1 define FALSE 0 main { int x=5; printf"x = d\n", x; if FALSE /** everything until the matching endif is commented **/ x = 304; endif printf"x = d\n", x; } Output: x = 5 x = 5 1.8 Problems 1. Run example programs to b ecome familiar with using C. 2. Write a program to print all Fahrenheit and Celsius temp eratures using conversion C =F 32 5=9 for 20 increments from 32 to 212 . See K&R, p. 9 if you are stuck. 3. Input a numb er and print all its factors 4. Input a numb er and decide if it is prime 5. Change the quadratic formula program so that it also prints the complex solutions 6. Input an integer and print the value of each digit in English: 932 => nine three two 7. Count the number of characters and lines in a le use '\n' to nd lines x1.8 A Crash Course in C 15 Table 2: Summary of C op erators K&R, p. 53 Operator Description Associativity Function call [] Array element reference left to right