Sie sind auf Seite 1von 10

Chapter 1

The Basics
The C code you write is called the SYNTAX. Syntax is a mixture of: C keywords like int, for and return. Constants and varia les ! more on these later. "#erators like + $arithmetic %addition%&, || $lo'ical %or%& and & $the %address of% o#erator&. Note that C is CAS( S(NS)T)*(+ )n other words, writin' in ca#itals as o##osed to lowercase makes a difference. Also, the amount of %white s#ace% you use in a C #ro'ram does not affect the way it,s com#iled. -ike .T/-, you can #ut as many s#aces in to make your #ro'rams more reada le.

Writing Your First Program


0efore you write your first #ro'ram, you must know what you want it to achieve+ )t,s like #uttin' a #encil on #a#er ! why start if you don,t know what you,re 'oin' to draw1+

Hello World
-et,s write and com#ile your first #ro'ram+ Ty#e the code shown in the screenshot into Note#ad $or emacs for 2N)X users& and save it with the .c extension.

The #include Directive


)f a line starts with a hash, #, it tells the com#iler that a command should e sent to the C 34(34"C(SS"4. The C #re#rocessor is a #ro'ram that is run when you com#ile. #include is one of the many C #re#rocessor commands you,ll use. 5hat this does is that it looks for the file s#ecified after it and #uts the contents of that file into the #lace where the #include directive is. )n a way, this makes the code more reada le. /ore #re#rocessor commands in the later sections.....

Header Files
.eader files have the extension .h and the full filename follows from the #include directive. .eader files contain declarations to certain functions that you may or may not have used in your #ro'ram. 6or exam#le, the stdio.h file is re7uired if you have used functions like printf and scanf in your #ro'ram. /ore a out these two functions in the STAN8A48 )N32T AN8 "2T32T section. There are two ways to include a header file:
#include "stdio.h"

and
Co#yri'ht -o'ic "#tion 3vt. -td.

#include <stdio.h>

)f you use the dou le 7uote marks, it means that the directory you,re currently in, will e searched for first for the header file, efore any other directories are searched. )f you use the s7uare rackets, directories other than the one you,re currently in, will e searched for the header file.

The main() function


All C #ro'rams must have a main() function. You can only have one, ut you can #lace it anywhere within the code. The #ro'ram always start with the main() function and ends when every statement in main() have een executed. All functions return a value ! this will e ex#lained later. main() is s#ecial as it returns an inte'er y default, which is why you,ll see me write return 0; at the end of the #ro'ram. :ero is returned as a way of sayin' that the #ro'ram ran successfully, without any errors. )f you wanted to terminate a #ro'ram, you can also use the exit() function. This takes one #arameter ! a num er. A'ain, ;ero is used if no errors occur, ut you must write #include <stdlib.h> at the to#.

Commenting Your Code


You can add comments to your code y enclosin' your remarks within ! and ! . .owever, nested comments aren,t allowed. Commentin' has a few advanta'es: They can e used to tell the #erson viewin' the code what #arts of the code does. This is hel#ful when you revisit the code at a later date. The com#iler i'nores all the comments. This means that comments do not affect the efficiency of the #ro'ram. You can use ! and ! to comment out sections of the code when it comes to findin' errors, instead of deletion. .ere are exam#les of commented code:
<= Comments s#annin' several =< <= lines can e commented =< <= out like this+ =< <= 0ut this is a more sim#ler way of doin' it+ =< << 0ut this is a C>> style comment ! not to e used with C+

Creating E ecuta!le Programs


There are several tasks that need to e #erformed efore you can run a #ro'ram:
Co#yri'ht -o'ic "#tion 3vt. -td.

9. You have to write the source code in C. You declare which header files you want to include within the source code. The source code must e saved with the extension .c. ?. Then you run the com#iler, which translates the source code into machine, or inary code, which the com#uter can understand. Com#uters do N"T understand C+ @. Sometimes the source code is still lackin' some #arts, so after 'oin' throu'h the com#iler, the code is #assed throu'h a -)NA(4. This asically %links% the source code to other li rary or o Bect files so that the final inary code is #roduced.

Constants and "aria!les


)t,s #retty o vious to think that constants stay constant where as varia les vary. $"kay, that was a stu#id way of sayin' that, ut it,s true+ ! (d&. Constants don,t chan'e their value, ut you can assi'n different values to a varia le. There are several rules that you must follow when namin' varia les: *aria le names.... (xam#le Cannot start with a num er ?times CAN contain a num er elsewhere times? Cannot contain any arithmetic o#erators ... a= >c ... or any s#ecial #unctuation marks+ result,CC. Cannot e a C keyword while Cannot contain a s#ace stu#id me CAN start with or contain an underscore DwhoDisDstu#id CAN e of mixed cases Thats4i'ht (x#ressions can consist of a mixture of constants, varia les and o#erators $more a out them later&. They return values. .ere are some exam#les of ex#ressions:
"# <= a constant =< x <= a varia le =< x > 9E <= a varia le #lus a constant =<

A statement is formed if you take an ex#ression and stick a semi!colon, ; , at the end of it+ 0asically, statements are instructions. .ere are some exam#les of statements:
x $ " + %; printf("&e 'ill learn about functions later()n"); int x* +* ,; <= more on %int% later =<

Statement locks, on the other hand, can contain a 'rou# of statements. The C com#iler com#iles the statement lock as if it was Bust one statement. To declare a statement lock you use the o#enin' race, - ut don,t for'et to close it with a corres#ondin' closin' race, . ++
Co#yri'ht -o'ic "#tion 3vt. -td.

The const #e$%ord


)f you declare a constant with the const keyword, it acts like a safe'uard, in case you accidentally assi'n a value to that varia le when you want to kee# it constant. .ere,s an exam#le declaration:
const int 'idth $ "0;

"nce this is declared, statement,s like 'idth $ "/; would e ille'al.

Data T$&es
There are four main data ty#es: char, int, float and double.

Characters
%A%, % %, %0% and %a%, alon' with all the other characters from the key oard, are classed as char s. The com#uter refers to the char s numerically and uni7uely and each character has a numerical value. Fust for fun, co#y this exam#le and save it as a source file. Then com#ile it and the #ro'ram should dis#lay the character set. 8on,t worry if you can,t 7uite understand the code.
#include <stdio.h> int main() int i*0; for(i$0 ; i</1 ; i++) for(0$0 ; 0<"0 ; 0++) printf("2d$2c "* "0!i+0* "0!i+0); printf(")n"); . return 0; .

)t is assumed that the % locks% occur when there is no character with that numerical value. )ncidentally, the newline character has the value of 9G. )t is also assumed that H is the acks#ace character and 'oodness knows what has ha##ened to the characters with value 99 throu'h to 9@+ The maximum numerical value of a character is ?II ! after that, the #attern re#eats itself. 0ut if you do use a character data ty#e $like in character arrays&, when you assi'n a varia le with a character, make sure you surround the individual characters with sin'le 7uote marks. The dou le 7uote marks are used for strin's, which will e ex#lained much later+
#include <stdio.h> int main() Co#yri'ht -o'ic "#tion 3vt. -td.

char a*b*c*d*e; a $ 343; <= correct way =< <= a K %.% is wron' =< K ,e,L c K ,l,L d K ,l,L e K ,o,L char strin'9MN K %world%L <= more on strin's later =< #rintf$%OcOcOcOcOc OsPn%, a, , c, d, e, strin'9&L return GL Q

'ntegers
5hole num ers are inte'ers, as you could,ve 'uessed.

Floating Point (um!ers


6or decimals, you need the data ty#e, float. 0ut you can also use double for decimals too. The difference1 5ell, if a varia le is declared as a float, it can e used to store a value of at least six decimal #laces. double s can have at least 9G decimal #laces. So why not use double all the time1 0ad idea unless you really have to, since double s use twice as much memory as float s. You need to e careful when it comes to #erformin' calculations involvin' a mixture of int s and float s. )f at any sta'e you assi'n a decimal num er to a varia le you ori'inally declared as an inte'er, you,re 'oin' to run into #ro lems. )t,s wise to assi'n a decimal value to a varia le you declare float. "n the other hand, if you try dividin' two inte'ers, you mi'ht ex#ect a decimal num er, ut an inte'er is returned+

Coersion
)f you did want to divide two inte'ers to'ether to #roduce a decimal, you can use the a #rocess called C"(4S)"N. Take a look at this exam#le:
#include <stdio.h> int main() int a*b; float c; a $ 1; b $ 5; c $ (float)a b;
Co#yri'ht -o'ic "#tion 3vt. -td.

printf("1 di6ided b+ 5 is 2f)n"* c); . return 0;

This exam#le mi'ht seem a little confusin' at first ! if that,s the case, i'nore the printf line for now. Anyway, the line that does the coersion usiness is:
c $ (float)a b; *aria les a and b are oth declared as inte'ers and have J and R assi'ned to them. c is a floatin' #oint num er. The (float) #art of the line, mentioned a ove, forces the floatin' #oint value of a b into c, which is already of the ty#e float )t is #ossi le to denote num ers in scientific notation, with the letter e ein' used to re#resent the

%ex#% utton on some calculators. )n 'eneral, xe+ means %x times $9G to the #ower of y&% where y can e #ositive or ne'ative. So ?IGG can e re#resented y /7e/ And G.GGC?H is 8/%e97 To learn a out the declaration of varia les and the in#ut and out#ut of the various data ty#es, see STAN8A48 )N32T AN8 "2T32T 0ut first, let,s move onto the asic arithmetic o#erators...

)rithmetic *&erators
The )ssignment *&erator
5hen you declare a varia le, you reserve a slot in the com#uter,s memory for value to e assi'ned to that varia le name, which is done y usin' the assi'nment o#erator. 6or exam#le, x $ "; takes the slot reserved for x and #uts the value " into it. 3retty o vious huh1+ Too o vious, that ) for'ot to mention anythin' a out the assi'nment o#erator in an earlier version of this site+ The assi'nment o#erator asically stores what ever value into the memory s#ace reserved for the varia le.

The )rithmetic *&erators


5hen #ro'rammin' in C you will use arithmetic o#erators re'ularly. There are I of them: + Addition 9 Su traction ! /ulti#lication 8ivision 2 /odulus
Co#yri'ht -o'ic "#tion 3vt. -td.

The less o vious one is the modulus o#erator. This is also known as the remainder o#erator and the conce#t in usin' it can e a little confusin' at first. No need to worry thou'h+ Su##ose you had x $ a 2 b; . This is asically tellin' the com#uter to work out how many times b 'oes into a and assi'n the 4(/A)N8(4 to x. So x $ 8 2 5; assi'ns " to x, since 5 'oes into 8 twice with " left over Not that confusin' after all then1+ The forthcomin' 7ui; should e a doddle+ 0e careful when mixin' o#erators. /ulti#lication, division and modulus are #erformed first, T.(N addition and su traction. 2se your common sense when it comes it the inclusion of rackets+ The stuff enclosed in rackets is worked out first, efore multi#lyin' etc.

)rithmetic )ssignment *&erators


You can also com ine the arithmetic o#erators with the assi'nment o#erator to sim#lify code. .ere are some exam#les: x $ x + +; x +$ +; )s the same as sayin' x 9$ +; x $ x 9 +; )s the same as sayin' x !$ +; x $ x ! +; )s the same as sayin' x $ +; x $ x +; )s the same as sayin' x 2$ +; x $ x 2 +; )s the same as sayin' A'ain, e careful, es#ecially with x !$ +; 6or exam#le, x !$ + + ,; is e7uivalent to sayin' x $ x ! (+ + ,); and N"T x $ (x ! +)
+ ,;

'ncrementing and Decrementing


)f you,ve declared an inte'er varia le $like x, say&, you can increment it y one y sayin' x++ $#ost!increment& or ++x $#re!increment&. Similarly, you can decrement it y one y sayin' x99 $#ost!decrement& or 99x $#re!decrement&. .owever, if you state somethin' alon' the lines like + $ x++; , the value of + will e the same as x 0(6"4( it was increased y one. You need to increase x y one 0(6"4( assi'nin' it to +, so you,d have to use the #re!increment o#erator. The same a##lies for decrementin'.

+elation and ,ogical *&erators


3ro'rams would e very orin' if they only #roduced one outcome, which is why we should e 'rateful for the conditional statements. These let us ranch off at one #oint in the #ro'ram, resultin' in different outcomes. Notice how much ranchin' 'oes on in our lives. 6or exam#le: %)f it is rainin' ) will stay indoors, else ) will walk the do'+%

+elational *&erators
6or us to make decisions, we act accordin' to a condition. )n the #revious exam#le, %it is rainin'% is a condition, where as %) will stay indoors% and %) will walk the do'% are results ased on the condition. 3ro'rammin' uses a similar conce#t. 5e can say:
Co#yri'ht -o'ic "#tion 3vt. -td.

%)f x #lus 9 is e7ual to I, then x e7uals J, else it is not e7ual to J%. The ta le elow sums u# the six relational o#erators used in C. (7ual to Not e7ual to -ess than -ess than or e7ual to Sreater than Sreater than or e7ual to
$ $ ( $ < < $ > > $

Note that the relation o#erators consist of a maximum of two characters with no s#ace etween them. Also, take care when usin' the %e7ual to% relational o#erator as #uttin' the assi'nment o#erator in is a common mistake.

,ogical *&erators
-o'ical o#erators allow you to com ine relation o#erators when it comes to writin' ex#ressions $or conditions& in if and else statements or when it comes to creatin' loo#s. 2sin' lo'ic o#erators allows you to %test% more than one condition. .ere are the three lo'ical o#erators and their 'eneral form: N"T AN8 "4
((expression) (expression") && (expression/) (expression") || (expression/)

And their truth ta les: $note that if ;ero is returned, the ex#ression can e thou'ht of as %false% and if one is returned, it,s %true%.& value returned from value returned from ex#ression N"T ex#ression 9 G G 9 value returned from value returned ex#ression9 ex#ression? 9 9 9 G G 9 G G
Co#yri'ht -o'ic "#tion 3vt. -td.

from value returned from AN8 ex#ression 9 G G G H

value returned from value returned ex#ression9 ex#ression? 9 9 9 G G 9 G G You,ll see some exam#les in the followin' sections.

from value returned from "4 ex#ression 9 9 9 G

T$&e -odifiers
The signed and unsigned #e$%ords
5hen you declare a varia le of the ty#e, int, y default, its value is S)SN(8. )n other words, the varia le could e #ositive or ne'ative. "n my machine, the minimum value of a si:ned int is !@?ERH and the maximum is @?ERH $K ?9I!9&. .owever, an unsi:ned int has the ran'e from G to RII@I $K?9R!9&.

The short and long #e$%ords


The cases a ove all a##ly when the inte'er is of the short ty#e. That is, it takes u# less memory than the lon: ty#e. Anyway, let,s reca# on the J cases: Ty#e 4an'e
si:ned short int unsi:ned short int si:ned lon: int unsi:ned lon: int

!@?ERH to @?ERE G to RII@I !?9JEJH@RJH ?9JEJH@RJE G to J?CJCRE?CI to

Note that: ?9I K @?ERH ?9R K RII@R ?@9 K ?9JEJH@RJH ?@? K J?CJCRE?CR

The si.eof *&erator


(ver wanted to know how much memory your varia les take u#1 Co#y and com#ile this #ro'ram:
Co#yri'ht -o'ic "#tion 3vt. -td.

#include <stdio.h> int main() printf(";i,e of int is 2d b+tes)n"* si,eof(int)); printf(";i,e of short int is 2d b+tes)n"* si,eof(short int)); printf(";i,e of lon: int is 2d b+tes)n)n"* si,eof(lon: int)); printf(";i,e of si:ned int is 2d b+tes)n"* si,eof(si:ned int)); printf(";i,e of si:ned short int is 2d b+tes)n"* si,eof(si:ned short int)); printf(";i,e of si:ned lon: int is 2d b+tes)n)n"* si,eof(si:ned lon: int)); printf(";i,e of unsi:ned int is 2d b+tes)n"* si,eof(si:ned int)); printf(";i,e of unsi:ned short int is 2d b+tes)n"* si,eof(unsi:ned short int)); printf(";i,e of unsi:ned lon: int is 2d b+tes)n)n"* si,eof(unsi:ned lon: int)); printf(";i,e of char is 2d b+tes)n"* si,eof(char)); printf(";i,e of float is 2d b+tes)n"* si,eof(float)); printf(";i,e of double is 2d b+tes)n"* si,eof(double)); return 0; .

5hen usin' the si,eof o#erator, all you have to do is #lace the data ty#e etween the rackets and it will return the num er of ytes a varia le of that ty#e will occu#y. Alternatively you can #lace a varia le name inside the rackets and it,ll tell you how much s#ace is reserved for that varia le. )sn,t that 'reat111+++

Co#yri'ht -o'ic "#tion 3vt. -td.

9G

Das könnte Ihnen auch gefallen