Getting Started

(lily) #1

Chapter 5: C Control Flow


A few practical examples: strlen, atoi, itoa, reverse......................................


In a serial communications project that we’ll get to later, we will want to convert
numbers into charac
ter strings to use in communicating with the PC. There are
ard Library, stdlib.h, that do everything we need; however,
rite them ourselves (with some help from K&R).


;
return i;

erminal character.

characters a backslash and a following

the t we will use several escape sequences, for
exampl cter that tells the Teletype machine to return


d to

functions in the Stand
to help us learn Let’s w


//NOTE: stolen from K&R p. 39 strlen function


int strLen(char s[])
{
int i;

i = 0;
while(s[i] != '\0')
++i

}

In strlen, we accept a pointer to a string (we’ll talk about pointers later). The
string is an array of characters with a terminal character ‘\0’ (we’ll talk about
arrays later). The while statement evaluates each character, incrementing the
index, i, until the terminal character is found. The return value is the number of
characters, not including the t


In C the single and double quotes have specific meaning: when you see ‘x’ the
compiler sees the ASCII number for the single character x; when you see “x” the
compiler sees a string with the character x followed by the string termination
character ‘\0’. Whenever you see two
character like ‘\0’, the C compiler sees this as a single nonprintable character
called an ‘escape sequence’.


In serial communications projec
e ‘\r’ is a non-printable chara
the print head to the left of the platen and roll the paper one line. What? You
aren’t using a Teletype machine? Maybe not, but you are using a direct ancestor
of one, and C was written on one, so thou shouldest get thyself use
anachronisms.

Free download pdf