Top Banner

of 39

c Pgramming

Aug 07, 2018

Download

Documents

victoriajude
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/21/2019 c Pgramming

    1/39

    CHAPTER 3: Functions

    1. What is the purpose of main() function?

    In C, program execution starts from the main() function.

    Every C program must contain a main() function. The mainfunction may contain any number of statements. Thesestatements are executed sequentially in the order whichthey are written.

    The main function can in-turn call other functions. henmain calls a function, it passes the execution control to thatfunction. The function returns control to main when a returnstatement is executed or when end of function is reached.In C, the function prototype of the !main! is one of the

    following"int main(); //main with no argumentsint main(int argc, char *argv[]); //main witharguments

    The parameters argcand argvrespectively give the number

    and value of the program!s command-line arguments.

    Eamp!e:

    #include /* program section egins here */int main() !// opening race " program eecution starts hereprint$(%&elcome to the world o$ '%);return ;// closing race " program terminates here

    "utput:

    elcome to the world of C

    #. Ep!ain comman$ !ine ar%uments of main function?

    In C, we can supply arguments to !main! function. Thearguments that we pass to main # $ at command prompt are

    1

  • 8/21/2019 c Pgramming

    2/39

    called command line arguments. These arguments aresupplied at the time of invo%ing the program.

    The main( )function can ta%e arguments as"

    main(int argc, char *argv[]) !

    The &rst argument argc is %nown as !argument counter!. Itrepresents the number of arguments in the command line.

    The second argument argvis %nown as 'argument vector'. It

    is an array of char type pointers that points to the commandline arguments. 'i(e of this array will be equal to the value ofargc.

    Eamp!e:

    at the command prompt if we give"

    '+> $ruit.ee apple mango

    Then

    argc would contain value )

    argv []

    would contain base address of string * fruit.exe* which is thecommand name that invo%es the program.

    argv []would contain base address of string *apple*

    argv [-]would contain base address of string *mango*

    here apple and mango are the arguments passed to theprogram fruit.exe

    Pro%ram:

    #include int main(int argc, char *argv[]) !int n;

    2

  • 8/21/2019 c Pgramming

    3/39

    print$(%ollowing are the arguments entered in thecommand line%);$or (n ; n < argc; n00) !print$(%+n 1s%, argv[n]);print$(%+n 2umer o$ arguments entered are+n 1d+n%,argc);return ;

    "utput:

    +ollowing are the arguments entered in the command line'+testpro3ect.ee

    applemango

    umber of arguments entered are )

    3. What are hea$er &!es? Are functions $ec!are$ or$e&ne$ in hea$er &!es ?

    +unctions and macros are declared in header &les. eader

    &les would be included in source &les by the compiler at thetime of compilation.eader &les are included in source code using #include

    directive. #include includes all the declarations

    present in the header &le4some.h4.

    header &le may contain declarations of sub-routines,functions, macros and also variables which we may want touse in our program. eader &les help in reduction ofrepetitive code.

    'nta of inc!u$e $irectie:

    #include //includes the header $ilestdio.h, standard input output header into thesource code

    3

  • 8/21/2019 c Pgramming

    4/39

    +unctions can be declared as well as de&ned in header &les./ut it is recommended only to declare functions and not tode&ne in the header &les. hen we include a header &le inour program we actually are including all the functions,

    macros and variables declared in it.In case of pre-de&ned C standard library header &lesex#stdio.h$, the functions calls are replaced by equivalentbinary code present in the pre-compiled libraries. Code for Cstandard functions are lin%ed and then the program isexecuted. eader &les with custom names can also becreated.Pro%ram: Custom hea$er &!es eamp!e

    /****************

    5nde restaurant.h****************/int ill6ll(int $ood7cost, int ta, int tip);/****************5nde restaurant.c****************/#includeint ill6ll(int $ood7cost, int ta, int tip) !int result;result $ood7cost 0 ta 0 tip;print$(%8otal ill is 1d+n%,result);return result;/****************5nde main.c****************/#include#include%restaurant.h%int main() !

    int $ood7cost, ta, tip;$ood7cost 9;ta ;tip 9;ill6ll($ood7cost,ta,tip);return ;

    4

  • 8/21/2019 c Pgramming

    5/39

    *. What are the $i+erences ,et-een forma!ar%uments an$ actua! ar%uments of a function?

    rgument" n argument is an expression which is passed toa function by its caller #or macro by its invo%er$ in order forthe function#or macro$ to perform its tas%. It is an expressionin the comma-separated list bound by the parentheses in afunction call expression.

    Actua! ar%uments:

    The arguments that are passed in a function call are calledactual arguments. These arguments are de&ned in thecalling function.

    Forma! ar%uments:

    The formal arguments are the parameters0arguments in afunction declaration. The scope of formal arguments is localto the function de&nition in which they are used. +ormalarguments belong to the called function. +ormal argumentsare a copy of the actual arguments. change in formalarguments would not be re1ected in the actual arguments.

    Eamp!e:

    #include void sum(int i, int 3, int :);/* calling $unction */int main() !int a 9;// actual argumentssum(, - * a, a);return ;

    /* called $unction *//* $ormal arguments*/void sum(int i, int 3, int :) !int s;s i 0 3 0 :;print$(%sum is 1d%, s);

    5

  • 8/21/2019 c Pgramming

    6/39

    ere ),23a,a are actual arguments and i,4,% are formalarguments.

    . What is pass , a!ue in functions?

    5ass by 6alue" In this method, the value of each of the actualarguments in the calling function is copied intocorresponding formal arguments of the called function. Inpass by value, the changes made to formal arguments in thecalled function have no e7ect on the values of actualarguments in the calling function.

    Eamp!e:

    #include void swap(int , int ) !int t;t ; ; t; int main()

    !int m , n -;print$(%=e$ore eecuting swap m1d n1d+n%, m, n);swap(m, n);print$(%6$ter eecuting swap m1d n1d+n%, m, n);return ;

    "utput:

    /efore executing swap m89: n82:fter executing swap m89: n82:

    Ep!anation:

    In the main function, value of variables m, n are not changedthough they are passed to function !swap!. 'wap function

    6

  • 8/21/2019 c Pgramming

    7/39

    has a copy of m, n and hence it can not manipulate theactual value of arguments passed to it.

    /. What is pass , reference in functions?

    Pass , Reference:

    In this method, the addresses of actual arguments in thecalling function are copied into formal arguments of thecalled function. This means that using these addresses, wewould have an access to the actual arguments and hence wewould be able to manipulate them. C does not support Callby reference. /ut it can be simulated using pointers.

    Eamp!e:#include /* $unction de$inition */void swap(int *, int *) !int t;t *; /* assign the value at address to t */* *; /* put the value at into */* t; /* put the value at to */ int main() !

    int m , n -;print$(%=e$ore eecuting swap m1d n1d+n%, m, n);swap(m, n);print$(%6$ter eecuting swap m1d n1d+n%, m, n);return ;

    "utput:

    /efore executing swap m89: n82:

    fter executing swap m82: n89:

    Ep!anation:

    In the main function, address of variables m, n are sent asarguments to the function !swap!. s swap function has theaccess to address of the arguments, manipulation of passed

    7

  • 8/21/2019 c Pgramming

    8/39

    arguments inside swap function would be directly re1ectedin the values of m, n.

    ;. hat are the di7erences between getchar#$ and scanf#$functions for reading string

    8

  • 8/21/2019 c Pgramming

    9/39

    0. "ut of the functions f%ets() an$ %ets() -hich one is

    safer to use an$ -h?

  • 8/21/2019 c Pgramming

    10/39

    copies a source string to a destination de&ned by user. Instrcpy function both source and destination strings arepassed as arguments. ?ser should ma%e sure thatdestination has enough space to accommodate the string to

    be copied. !strcpy! sounds li%e short form of *string copy*.

    'nta:

    strcp(char *destination, const char *source);

    'ource string is the string to be copied and destination stringis string into which source string is copied. If successful,strcpy subroutine returns the address of the copied string.

  • 8/21/2019 c Pgramming

    11/39

    str$up function:

    duplicates a string to a location that will be decided by thefunction itself. +unction will copy the contents of string tocertain memory location and returns the address to thatlocation. 4strdup4 sounds li%e short form of "stringduplicate"

    'nta:

    strdup (const char *s);

    strdup returns a pointer to a character or base address of anarray.

    +unction returns address of the memory location where thestring has been copied. In case free space could not becreated then it returns a null pointer.

    /oth strcpand strdupfunctions are present in header &le

    Pro%ram:

    Pro%ram to i!!ustrate str$up().

    #include#include#includeint main() !char mname[] %6?@52A%;//name is pointer variale which can store theaddress o$ memor location o$ stringchar* name;//contents o$ mname are copied in a memor address

    and are assigned to namename strdup(mname);//prints the contents o$ 4name4puts(name);//prints the contents o$ 4mname4puts(mname);//memor allocated to 4name4 is now $reed

    11

  • 8/21/2019 c Pgramming

    12/39

    $ree(name);return ;

    "utput:

    @6IA@6IA

    Ep!anation:

    'tring myname consists of *@6IA* stored in it. Contents ofmyname are copied in a memory address and memory isassigned to name. t the end of the program, memory canbe freed using

    $ree(name);1. What is the difference between declaring a variable and defining a variable?

    Ans: Declaration of a variable in C hints the compiler about the type and size ofthe variable in compile time. Similarly,declaration of a function hints about type and size of function parameters. ospace is reserved in memory for any variable in case of declaration.Example! int a"#ere variable $a$ is declared of data type $int$Defining a variable means declaring it and also allocating space to hold it.We can say %Definition & Declaration ' Space reservation%.Example: int a & 1("#ere variable %a% is described as an int to the compiler and memory is allocatedto hold value 1(.). What is a static variable?

    * static variable is a special variable that is stored in the data segment unli+e thedefault automatic variable thatis stored in stac+. * static variable can be initialized by using +eyword staticbefore variable name.Example:static int a 9;

    12

  • 8/21/2019 c Pgramming

    13/39

    * static variable behaves in a different manner depending upon whether it is aglobal variable or a local variable.

    * static global variable is same as an ordinary global variable ecept that it

    cannot be accessed by other files in the same program - proect even with theuse of +eyword etern. * static local variable is different from local variable. /t isinitialized only once no matter how many times that function in which it resides iscalled. /t may be used as a count variable.Example:

    #include //program in $ile $.cvoid count(void) !static int count ;int count- ;count00;count-00;print$(%+n@alue o$ count is 1d, @alue o$ count- is 1d%,count, count-);/*Bain $unction*/int main()!count();count();count();return ;

    Output:

    0alue of count1 is 1, 0alue of count) is 10alue of count1 is ), 0alue of count) is 10alue of count1 is , 0alue of count) is 1

    . What is a register variable?

    2egister variables are stored in the C34 registers. /ts default value is a garbage

    value. Scope of a register variable is local to the bloc+ in which it is defined.5ifetime is till control remains within the bloc+ in which the register variable isdefined. 0ariable stored in a C34 register can always be accessed faster thanthe one that is stored in memory. 6herefore, if a variable is used at many placesin a program, it is better to declare its storage class as registerExample:

    13

  • 8/21/2019 c Pgramming

    14/39

    register int 9;

    0ariables for loop counters can be declared as register. ote that register+eyword may be ignored by some compilers.

    7. Where is an auto variables stored?

    8ain memory and C34 registers are the two memory locations where autovariables are stored. *uto variables are defined under automatic storage class.6hey are stored in main memory. 8emory is allocated to an automatic variablewhen the bloc+ which contains it is called and it is de9allocated at the completionof its bloc+ eecution.Auto variables:

    Storage : main memory.Default value : garbage value.Scope : local to the bloc+ in which the variable is defined.Lifetime : till the control remains within the bloc+ in which the variable is defined.:. What is scope ; storage allocation of etern and global variables?

  • 8/21/2019 c Pgramming

    15/39

    +now the datatype of and this is done by etern definition.

    =lobal variables! are variables which are declared above the main> function.6hese variables are accessible throughout the program. 6hey can be accessedby all the functions in the program. 6heir default value is zero.

    Example:

    #include int ;/* @ariale is a gloal variale.5t can e accessed throughout the program */void increment(void) ! 0 ;print$(%+n value o$ 1d%, ); int main()!print$(%+n value o$ 1d%, );increment();return ;

    @. What is scope ; storage allocation of register, static and local variables?

    Register variables:

    belong to the register storage class and are stored in the C34 registers. 6hescope of the register variables is local to the bloc+ in which the variables aredefined. 6he variables which are used for more number of times in a program aredeclared as register variables for faster access.Example: loop counter variables.

    register int C;

    Static variables:

    8emory is allocated at the beginning of the program eecution and it isreallocated only after the program terminates. 6he scope of the static variables is

    local to the bloc+ in which the variables are defined.Example:#include void decrement()!static int a9;a"";print$(%@alue o$ a1d+n%, a);

    15

  • 8/21/2019 c Pgramming

    16/39

    int main()!decrement();return ;

    #ere $a$ is initialized only once.

  • 8/21/2019 c Pgramming

    17/39

    1(. What is the difference between $for$ and $while$ loops?

    for loop:

    When it is desired to do initialization, condition chec+ and increment-decrementin a single statement of an iterative loop, it is recommended to use $for$ loop.Syntax:

    $or(initialiDation;condition;increment/decrement)!/

    17

  • 8/21/2019 c Pgramming

    18/39

    /loc: o$ statementsincrement or decrementErogram Erogram to illustrate $or loop#include

    int main() !int i;$or (i ; i

  • 8/21/2019 c Pgramming

    19/39

    Output:

  • 8/21/2019 c Pgramming

    20/39

    written in three bases >decimal, octal, and hexadecimal. *lthough theprogrammer can choose to specify numbers in these three bases, once loadedinto the computer, the all numbers are stored and processed as unsigned orsigned binary. *lthough C does not support the binary literals, if you wanted tospecify a binary number, you should have no trouble using either the octal or

    headecimal format.

    Binary representation

    umbers are stored on the computer in binary form. /n other words, informationis encoded as a seFuence of 1Gs and (Gs. En most computers, the memory isorganized into B9bit bytes. 6his means each B9bit byte stored in memory will havea separate address. Precisionis the number of distinct or different values. Weepress precision in alternatives, decimal digits, bytes, or binary bits.

    Alternativesare defined as the total number of possibilities. Hor eample, an B9bitnumber scheme can represent ):@ different numbers. *n B9bit digital to analog

    converter can generate ):@ different analog outputs. *n B9bit analog to digitalconverter >*DC can measure ):@ different analog inputs. We use theepression 7I decimal digits to mean about )(,((( alternatives and theepression 7J decimal digits to mean more than )(,((( alternatives but lessthan 1((,((( alternatives. 6he I decimal digit means twice the number ofalternatives or one additional binary bit. Hor eample, a voltmeter with a range of(.(( to .0 has a three decimal digit precision. 5et the operation KKLL be thegreatest integer of .

  • 8/21/2019 c Pgramming

    21/39

    n KKn-BLL )n

    Table 3-1a. Relationships between various representations of precision.

    'ecimal%igits

    Alternatives

    1(((I )(((J 7(((7 1((((7I )((((

    7J 7((((: 1(((((n 1(n

    Table 3-1b. Relationships between various representations of precision.

    Observation A good rule of thumb to remember is !1"#n is about 1"3#n.Hor large numbers we use abbreviations, as shown in the following table. Horeample, 1@M means 1@N1()7 which eFuals 1@B7. Computer engineers use thesame symbols as other scientists, but with slightly different values.

    abbreviation pronunciation !omputer Engineering (alue Scientific (alue

    M %+ay% )1(1()7 1(

    8 %meg% ))(1,(7B,:A@ 1(@

    = %gig% )(1,(A,A71,B)7 1(

    6 %tera% )7(1,(,:11,@)A,AA@ 1(1)

    3 %peta% ):(1,1):,B,(@,B7,@)7 1(1:

    < %ea% )@(1,1:),)1,:(7,@(@,B7@,A@ 1(1BTable 3-!. $ommon abbreviations for large numbers.

    8-it unsigne! numers* byte contains B bits

    21

  • 8/21/2019 c Pgramming

    22/39

    where each bit bA,...,b( is binary and has the value 1 or (. We specify bA as themost significant bitor 8S, and b( as the least significant bit or 5S. /f a byte isused to represent an unsigned number, then the value of the number is

    & 1)BObA ' @7Ob@ ' )Ob: ' 1@Ob7 ' BOb ' 7Ob) ' )Ob1 ' b(6here are ):@ different unsigned B9bit numbers. 6he smallest unsigned B9bitnumber is ( and the largest is )::. Hor eample, ((((1(1()is B') or 1(. Ethereamples are shown in the following table.binary he Calculation decimal

    (((((((( ((( (

    (1(((((1 (71 @7'1 @:

    (((1(11( (1@ 1@'7') ))

    1((((111 (BA 1)B'7')'1 1:

    11111111 (HH 1)B'@7')'1@'B'7')'1 )::Table 3-3. %xample conversions from unsigned &-bit binar' to hexadecimal and

    to decimal.

    6he basisof a number system is a subset from which linear combinations of thebasis elements can be used to construct the entire set. Hor the unsigned B9bitnumber system, the basis is

    P 1, ), 7, B, 1@, ), @7, 1)BQEne way for us to convert a decimal number into binary is to use the basiselements. 6he overall approach is to start with the largest basis element andwor+ towards the smallest. Ene by one we as+ ourselves whether or not we needthat basis element to create our number. /f we do, then we set the corresponding

    bit in our binary result and subtract the basis element from our number. /f we donot need it, then we clear the corresponding bit in our binary result. We will wor+through the algorithm with the eample of converting 1(( to B bit binary. We withthe largest basis element >in this case 1)B and as+ whether or not we need toinclude it to ma+e 1((. Since our number is less than 1)B, we do not need it sobit A is zero. We go the net largest basis element, @7 and as+ do we need it. Wedo need @7 to generate our 1((, so bit @ is one and subtract 1(( minus @7 to get@. et we go the net basis element, ) and as+ do we need it. *gain we doneed ) to generate our @, so bit : is one and we subtract @ minus ) to get 7.Continuing along, we need basis element 7 but not 1@ B ) or 1, so bits 7)1( are((1(( respectively. 3utting it together we get (11((1(() >which means

    @7')'7.

    Observation (f the least significant binar' bit is )ero* then the number iseven.

    Observation (f the right most n bits +least significant, are )ero* then thenumber is divisible b' !n.

    22

  • 8/21/2019 c Pgramming

    23/39

    #umber &asis #ee% it bit Operation

    1(( 1)B no bitA&( none

    1(( @7 yes bit@&1 subtract 1((9@7

    @ ) yes bit:&1 subtract @9)

    7 1@ no bit7&( none7 B no bit&( none

    7 7 yes bit)&1 subtract 797

    ( ) no bit1&( none

    ( 1 no bit(&( noneTable 3-. %xample conversion from decimal to unsigned &-bit binar' tohexadecimal.

    We define an unsigned B9bit number using theunsigned char format. When anumber is stored into an unsigned charit is converted to B9bit unsigned value.

    Hor eample

    unsigned char data; // to -99unsigned char $unction(unsigned char input)! datainput0; return data;

    )*bit signe% numbers

    /f a byte is used to represent a signed !s complementnumber, then the value ofthe number is

    & 91)BObA ' @7Ob@ ' )Ob: ' 1@Ob7 ' BOb ' 7Ob) ' )Ob1 ' b(6here are also ):@ different signed B bit numbers. 6he smallest signed B9bitnumber is 91)B and the largest is 1)A. Hor eample, 1(((((1( ) is 91)B') or91)@. Ether eamples are shown in the following table.

    binary he Calculation decimal

    (((((((( ((( (

    (1(((((1 (71 @7'1 @:

    (((1(11( (1@ 1@'7') ))1((((111 (BA 91)B'7')'1 91)1

    11111111 (HH 91)B'@7')'1@'B'7')'1 91Table 3-/. %xample conversions from signed &-bit binar' to hexadecimal and todecimal.

    Hor the signed B9bit number system the basis is

    23

  • 8/21/2019 c Pgramming

    24/39

    P 1, ), 7, B, 1@, ), @7, 91)BQ

    Observation The most significant bit in a !s complement signed numberwill specif' the sign.

    otice that the same binary pattern of 11111111)could represent either ):: or 91./t is very important for the software developer to +eep trac+ of the number format.6he computer can not determine whether the B9bit number is signed or unsigned.Rou, as the programmer, will determine whether the number is signed orunsigned by the specific assembly instructions you select to operate on thenumber. Some operations li+e addition, subtraction, and shift left >multiply by )use the same hardware >instructions for both unsigned and signed operations.En the other hand, multiply, divide, and shift right >divide by ) reFuire separatehardware >instruction for unsigned and signed operations. Hor eample, the@B(:-@B(B-@B11 multiply instruction, mul, operates only on unsigned values. Soif you use the mulinstruction, you are implementing unsigned arithmetic. 6heHreescale @B1) has both unsigned, mul, and signed, smul, multiply instructions.So if you use the smulinstruction, you are implementing signed arithmetic. 6hecompiler will automatically choose the proper implementation.It is always good programming practice to have clear understanding o the data type oreach num!er" varia!le" parameter" etc# $or some operations there is a dierence !etween

    the signed and unsigned num!ers while or others it does not matter#

    signe% %ifferent from unsigne% signe% same as unsigne%

    - division ' addition

    N multiplication 9 subtraction

    T greater than && is eFual to

    U less than V logical or

    T& greater than or eFual to ; logical and

    U& less than or eFual to logical eclusive or

    TT right shift UU left shiftTable 3-0. Operations either depend or dont depend on whether the number issigned2unsigned.

    6he point is that care must be ta+en when dealing with a miture of numbers of

    different sizes and types.Similar to the unsigned algorithm, we can use the basis to convert a decimalnumber into signed binary. We will wor+ through the algorithm with the eampleof converting 91(( to B9bit binary. We with the largest basis element >in this case91)B and decide do we need to include it to ma+e 91((. Res >without 91)B, wewould be unable to add the other basis elements together to get any negativeresult, so we set bit A and subtract the basis element from our value. Eur newvalue is 91(( minus 91)B, which is )B. We go the net largest basis element, @7

    24

  • 8/21/2019 c Pgramming

    25/39

    and as+ do we need it. We do not need @7 to generate our )B, so bit@ is zero.et we go the net basis element, ) and as+ do we need it. We do not need )to generate our )B, so bit: is zero. ow we need the basis element 1@, so we setbit7, and subtract 1@ from our number )B >)B91@&1). Continuing along, we needbasis elements B and 7 but not ) 1, so bits )1( are 11((. 3utting it together we

    get 1((111(() >which means 91)B'1@'B'7.

    #umber &asis #ee% it bit Operation

    91(( 91)B yes bitA&1 subtract 91(( 9 91)B

    )B @7 no bit@&( none

    )B ) no bit:&( none

    )B 1@ yes bit7&1 subtract )B91@

    1) B yes bit&1 subtract 1)9B

    7 7 yes bit)&1 subtract 797

    ( ) no bit1&( none

    ( 1 no bit(&( noneTable 3-. %xample conversion from decimal to signed &-bit binar' tohexadecimal.

    "servation:To ta4e the negative of a !s complement signed numberwe first complement +flip, all the bits* then add 1.

    * second way to convert negative numbers into binary is to first convert them intounsigned binary, then do a )Gs complement negate. Hor eample, we earlierfound that '1(( is (11((1((). 6he )Gs complement negate is a two step process.Hirst we do a logic complement >flip all bits to get 1((11(11). 6hen add one tothe result to get 1((111(().

    * third way to convert negative numbers into binary is to first subtract the numberfrom ):@, then convert the unsigned result to binary using the unsigned method.Hor eample, to find 91((, we subtract ):@ minus 1(( to get 1:@. 6hen weconvert 1:@ to binary resulting in 1((111((). 6his method wor+s because in B bitbinary math adding ):@ to number does not change the value.

  • 8/21/2019 c Pgramming

    26/39

    We define a signed B9bit number using the charformat. When a number is storedinto a charit is converted to B9bit signed value. Hor eample

    char data; // "-G to -Ichar $unction(char input)! datainput0; return data;

    #$ it unsigne! numers* wordor double b'tecontains 1@ bits

    where each bit b1:,...,b( is binary and has the value 1 or (. /f a word is used torepresent an unsigned number, then the value of the number is

    & )A@BOb1: ' 1@B7Ob17 ' B1)Ob1 ' 7(@Ob1)' )(7BOb11 ' 1()7Ob1( ' :1)Ob ' ):@ObB' 1)BObA ' @7Ob@ ' )Ob: ' 1@Ob7 ' BOb ' 7Ob) ' )Ob1 ' b(

    6here are @:,:@ different unsigned 1@9bit numbers. 6he smallest unsigned 1@9bit number is ( and the largest is @:::. Hor eample, ((1(,(((1,1(((,(1(( )or()1B7 is B1)'):@'1)B'7 or B:B(. Ether eamples are shown in the followingtable.

    binary ex !alculation %ecimal

    ((((,((((,((((,(((( ((((( (

    ((((,(1((,((((,(((1 ((7(1 1()7'1 1():

    ((((,11((,1(1(,(((( ((C*( )(7B'1()7'1)B') ))

    1(((,111(,((((,((1( (B

  • 8/21/2019 c Pgramming

    27/39

    P 1, ), 7, B, 1@, ), @7, 1)B, ):@, :1), 1()7, )(7B, 7(@, B1), 1@B7,)A@BQ

    /f a word is used to represent a signed )Gs complement number, then the value ofthe number is

    & 9)A@BOb1: ' 1@B7Ob17 ' B1)Ob1 ' 7(@Ob1)' )(7BOb11 ' 1()7Ob1( ' :1)Ob ' ):@ObB' 1)BObA ' @7Ob@ ' )Ob: ' 1@Ob7 ' BOb ' 7Ob) ' )Ob1 ' b(

    We define an unsigned 1@9bit number using the unsigned shortformat. When anumber is stored into an unsigned shortit is converted to 1@9bit unsigned value.Hor eample

    unsigned short data; // to C999

    unsigned short $unction(unsigned short input)! datainput0; return data;

    1+*bit signe% numbers

    6here are also @:,:@ different signed 1@9bit numbers. 6he smallest signed 1@9bit number is 9)A@B and the largest is )A@A. Hor eample,11(1,((((,((((,(1(()or (D((7 is 9)A@B'1@B7'7(@'7 or 91))B7. Ethereamples are shown in the following table.binary ex !alculation %ecimal

    ((((,((((,((((,(((( ((((( (

    ((((,(1((,((((,(((1 ((7(1 1()7'1 1():((((,11((,1(1(,(((( ((C*( )(7B'1()7'1)B') ))

    1(((,(1((,((((,((1( (B7() 9)A@B'1()7') 91A7)

    1111,1111,1111,1111 (HHHH 9)A@B'1@B7'B1)'7(@')(7B'1()7':1)'):@'1)B'@7')'1@'B'7')'1

    91

    Table 3-6. %xample conversions from signed 10-bit binar' to hexadecimal and todecimal.

    Hor the signed 1@9bit number system the basis is

    P 1, ), 7, B, 1@, ), @7, 1)B, ):@, :1), 1()7, )(7B, 7(@, B1), 1@B7,9)A@BQ

    %aintenance &ip To improve the 7ualit' of our software* we shouldalwa's specif' the precision of our data when defining or accessing thedata.

    27

  • 8/21/2019 c Pgramming

    28/39

    We define a signed 1@9bit number using theshort format. When a number isstored into a shortit is converted to 1@9bit signed value. Hor eample

    short data; // "-ICG to -ICIshort $unction(short input)! datainput0; return data;

    &ig an% Little En%ian

    When we store 1@9bit data into memory it reFuires two bytes. Since the memorysystems on most computers are byte addressable >a uniFue address for eachbyte, there are two possible ways to store in memory the two bytes thatconstitute the 1@9bit data. Hreescale microcomputers implement the big endianapproach that stores the most significant part first. /ntel microcomputersimplement the little endianapproach that stores the least significant part first. 6he

    3ower3C is biendian, because it can be configured to efficiently handle both bigand little endian. Hor eample, assume we wish to store the 1@ bit number 1(((>((B9bit addressable. /f we wish to store the )9bit number (1)7:@AB at locations (:(9(: then

    /n the above two eamples we normally would not pic+ out individual bytes >e.g.,the (1), but rather capture the entire multiple byte data as one nondivisablepiece of information. En the other hand, if each byte in a multiple byte data

    structure is individually addressable, then both the big and little endian schemesstore the data in first to last seFuence. Hor eample, if we wish to store the 7

    *SC// characters X@B11G which is (@B11 at locations (:(9(:, then the*SC// X@G&(@ comes first in both big and little endian schemes.

    28

  • 8/21/2019 c Pgramming

    29/39

    6he term %ig

  • 8/21/2019 c Pgramming

    30/39

    Halse be all zeros, and6rue be any nonzero value.

    8any programmers add the following macros

    #de$ine 8?LJ #de$ine 6MNJ

    'ecimal #umbers

    Decimal numbers are written as a seFuence of decimal digits >( through . 6henumber may be preceded by a plus or minus sign or followed by a Lor ,. 5owercase l or u could also be used. 6he minus sign gives the number a negativevalue, otherwise it is positive. 6he plus sign is optional for positive values.4nsigned 1@9bit numbers between )A@B and @::: should be followed by ,.Rou can place a Lat the end of the number to signify it to be a )9bit signed

    number. 6he range of a decimal number depends on the data type as shown inthe following table.

    type range precision examplesunsigned char ( to ):: B bits ( 1( 1)char 91)A to 1)A B bits 91) ( 1( '1(unsigned int ( to @:::4 1@ bits ( )((( )(((4

    :((((4int 9)A@A to )A@A 1@ bits 91((( ( 1((( ')((((

    unsigned short ( to @:::4 1@ bits ( )((( )(((4:((((4

    short 9)A@A to )A@A 1@ bits 91((( ( 1((( ')((((long 9)17A7B@7A5 to

    )17A7B@7A5) bits 91)7:@A5 (5

    1)7:@A5Table 3-1". The range of decimal numbers.ecause the @B11 and @B1) microcomputers are most efficient for 1@ bit data>and not ) bit data, the unsigne% intand intdata types are 1@ bits. En theother hand, on a B@9based machine, the unsigne% intand intdata types are )bits. /n order to ma+e your software more compatible with other machines, it is

    preferable to use the sorttype when needing 1@ bit data and the longtype for) bit data.type +)11-+)12 x)+unsigned char B bits B bitschar B bits B bitsunsigned int 1@ bits ) bitsint 1@ bits ) bitsunsigned short 1@ bits 1@ bits

    30

  • 8/21/2019 c Pgramming

    31/39

    short 1@ bits 1@ bitslong ) bits ) bitsTable 3-11. :ifferences between a 0&1120&1! and an x&0Since the @B11 and @B1) microcomputers do not have direct support of )9bit

    numbers, the use of long data types should be minimized. En the other hand, acareful observation of the code generated yields the fact that these compilers aremore efficient with 1@ bit numbers than with B bit numbers.Decimal numbers are reduced to their two$s complement or unsigned binaryeFuivalent and stored as B-1@-)9bit binary values.6he manner in which decimal literals are treated depends on the contet. Horeample

    short 5;unsigned short O;

    char P;unsigned char M;long B;void main(void)!

    5HI; /* C its C */ OHI; /* C its C */ PHI; /* G its C */ MHI; /* G its C */ BHI; /* - its C */

    6he @B1) code generated by the /CC1) compiler is as follows

    .area tet7main

    psht$r s,movw #HI,75 ;C its

    movw #HI,7O ;C itsmov #HI,7P ;G itsmov #HI,7M ;G itsld #M-3sr 77l-reg ;- its

    ld #7B3sr 77lreg-t$r ,s

    pulrts.area ss

    7B .l: F7M .l: 7P .l: 7O .l: -75 .l: -

    .area tetM- .word ,HI

    31

  • 8/21/2019 c Pgramming

    32/39

    6he @B1) code generated by the 8etrower+s compiler is much more efficientwhen dealing with ) bit long integers

    MA6= #HI

    'M?6N8A 5

    N8A O N86= P N86= M N8A B- 'M?=

    N8A B ?8N

    Octal #umbers

    /f a seFuence of digits begins with a leading >zero it is interpreted as an octalvalue. 6here are only eight octal digits, ( through A. *s with decimal numbers,octal numbers are converted to their binary eFuivalent in B9bit or 1@9bit words.6he range of an octal number depends on the data type as shown in thefollowing table.type range precision examplesunsigned char ( to (AA B bits ( (1( (1)char 9()(( to (1AA B bits 9(1) ( (1( '(1(unsigned int ( to (1AAAAA 1@ bits ( ()((( (1:((((4int 9(AAAAA to (AAAAA 1@ bits 9(1((( ( (1(((

    '()((((unsigned short ( to (1AAAAA 1@ bits ( ()((( (1:((((4short 9(AAAAA to (AAAAA 1@ bits 9(1((( ( (1(((

    '()((((long 9(1AAAAAAAAAA5 to

    (1AAAAAAAAAA5) bits 9(1)7:@A5 (5

    (1)7:@A5Table 3-1!. The range of octal numbers.otice that the octal values ( through (A are eFuivalent to the decimal values (through A. Ene of the advantages of this format is that it is very easy to convertbac+ and forth between octal and binary.

  • 8/21/2019 c Pgramming

    33/39

    between binary and headecimal. * nibble is defined as 7 binary bits.

  • 8/21/2019 c Pgramming

    34/39

    6o convert from headecimal to binary we can!

    1 convert each headecimal digit into its corresponding 7 bit binarynibble") combine the nibbles into a single binary number.

    /f a seFuence of digits begins with x or 0 then it is ta+en as a headecimal

    value. /n this case the word digits refers to headecimal digits >( through H. *swith decimal numbers, headecimal numbers are converted to their binaryeFuivalent in B9bit bytes or1@9bit words. 6he range of a headecimal numberdepends on the data type as shown in the following table.

    type rangeprecision

    examples

    unsignedchar

    ((( to (HH B bits ((1 (a (

    char 9(AH to (AH B bits 9((1 (a 9(A

    unsigned int ((((( to (HHHH 1@ bits ()) ([abcd (H(*@

    int 9(AHHH to (AHHH 1@ bits 9()) ([( '(A(*@

    unsignedshort

    ((((( to (HHHH 1@ bits ()) ([abcd (H(*@

    short 9(AHHH to (AHHH 1@ bits 9(1)7 (( '(Aabc

    long9(AHHHHHHH to(AHHHHHHH

    ) bits9(1)7:@A(*CD

  • 8/21/2019 c Pgramming

    35/39

    long B;void main(void)!

    54a4; /* C its C */ O4a4; /* C its C */ P4a4; /* G its C */ M4a4; /* G its C */ B4a4; /* - its C */

    6he @B1) code generated by the /CC1) compiler is as follows

    .area tet7main

    psht$r s,movw #HI,75 ;C its

    movw #HI,7O ;C itsmov #HI,7P ;G itsmov #HI,7M ;G its

    ld #M-3sr 77l-reg ;- its ld #7B

    3sr 77lreg-t$r ,spulrts.area ss

    7B .l: F7M .l: 7P .l: 7O .l: -75 .l: -

    .area tet

    M- .word ,HI6he @B1) code generated by the 8etrower+s compiler is as follows

    MA6= #HI 'M?6

    N8A 5 N8A O N86= P N86= M N8A B- 'M?=

    N8A B ?8N

    *ll standard *SC// characters are positive because the high9order bit is zero. /nmost cases it doesn$t matter if we declare character variables as signed orunsigned. En the other hand, we have seen earlier that the compiler treatssigned and unsigned numbers differently. 4nless a character variable isspecifically declared to be unsigned, its high9order bit will be ta+en as a sign bit.

    35

  • 8/21/2019 c Pgramming

    36/39

    6herefore, we should not epect a character variable, which is not declaredunsigned, to compare eFual to the same character literal if the high9order bit isset. Hor more on this see Chapter 7 on 0ariables.

    String Literals

    Strictly spea+ing, C does not recognize character strings, but it does recognizearrays of characters and provides a way to write character arrays, which we callstrings. Surrounding a character seFuence with Fuotation mar+s, e.g., on,sets up an array of characters and generates the address of the array. /n otherwords, at the point in a program where it appears, a string literal produces theaddress of the specified array of character literals. 6he array itself is locatedelsewhere. /CC11 and /CC1) will place the strings into the tet area. /.e., thestring literals are considered constant and will be defined in the 2E8 of anembedded system. 6his is very important to remember. otice that this differsfrom a character literal which generates the value of the literal directly. Yust to be

    sure that this distinct feature of the C language is not overloo+ed, consider thefollowing eample!

    char *pt;void main(void)!

    pt%Oon%; /* pointer to the string */ print$(pt); /* passes the pointer not the data itsel$ */

    6he @B1) code generated by the /CC1) compiler is as follows

    .area tet7main

    movw #M-,7ptldd 7pt

    3sr 7print$ rts

    .area ss7pt .l: -

    .area tetM- .te 4O,4o,4n,

    6he @B1) code generated by the 8etrower+s compiler is virtually the same as/CC1). oth compilers place the string in memory and use a pointer to it whencalling printf. /CC1) will pass the parameter in 2egD,while 8etrower+s pushesthe parameter on the stac+.

    BQ@& #%Oon%,ptMAA pt

    ENKA

    36

  • 8/21/2019 c Pgramming

    37/39

    ON? print$ ELMA ?8N

    otice that the pointer, pt, is allocated in 2*8 >.area bss and the string is storedin 2E8 >.area tet. 6he assignment statement pt%Oon%;copies the address notthe data. Similarly, the function print$()must receive the address of a string as

    its first >in this case, only argument. Hirst, the address of the string is assigned tothe character pointer pt >/CC11-/CC1) use the 1@ bit 2egister D for the firstparameter. 4nli+e other languages, the string itself is not assigned to pt, only itsaddress is. *fter all, ptis a 1@9bit obect and, therefore, cannot hold the stringitself. 6he same program could be written better as

    void main(void)!print$(%Oon%); /* passes the pointer not the data itsel$ */

    otice again that the program passes a pointer to the string into print$(), andnot the string itself. 6he @B1) code generated by the /CC1) compiler is as follows

    .area tet7main

    ldd #M- 3sr 7print$ rts

    .area tetM- .te 4O,4o,4n,

  • 8/21/2019 c Pgramming

    38/39

    char letter,*pt;void main(void)!

    pt%6%; /* pointer to the string */

    letter464; /* the data itsel$ (464 6N'55 C9RF) */

    6he @B1) code generated by the /CC1) compiler is as follows

    .area tet7main

    movw #M-,7ptmov #C9,7letter

    rts.area ss

    7letter .l:

    7pt .l: -.area tet

    M- .te 46,

    6he @B1) code generated by the 8etrower+s compiler is as follows

    BQ@& #%6%,ptMA6= #C9

    N86= letter ?8N

    Escape Se4uences

    Sometimes it is desirable to code nongraphic characters in a character or stringliteral. 6his can be done by using an escape se7uence99a seFuence of two ormore characters in which the first >escape character changes the meaning of thefollowing character>s. When this is done the entire seFuence generates only onecharacter. C uses the bac+slash >5 for the escape character. 6he followingescape seFuences are recognized by the /CC11-/CC1)-8etrower+s compilers!seFuence name value

    \n newline, linefeed Z(* & 1(

    \t tab Z( &

    \b bac+space Z(B & B

    \f form feed Z(C & 1)\a bell Z(A & A

    \r return Z(D & 1

    \v vertical tab Z( & 11

    \( null Z(( & (

    \% *SC// Fuote Z)) & 7

    \\ *SC// bac+ slash Z:C & )

    38

  • 8/21/2019 c Pgramming

    39/39

    \$ *SC// single Fuote Z)A & Table 3-10. The escape se7uences supported b' ($$11 ($$1! and 5etrower4s.

    Ether nonprinting characters can also be defined using the5ooooctal format. 6he

    digits ooo can define any B9bit octal number. 6he following three lines areeFuivalent!

    print$(%+tOon+n%); print$(%+Oon+-%);

    print$(%+Oon+-%);

    6he term newlinerefers to a single character which, when written to an outputdevice, starts a new line. Some hardware devices use the *SC// carriage return>1 as the newline character while others use the *SC// line feed >1(. /t reallydoesn$t matter which is the case as long as we write +nin our programs. *void

    using the *SC// value directly since that could produce compatibility problemsbetween different compilers.6here is one other type of escape seFuence! anything undefined. /f thebac+slash is followed by any character other than the ones described above,then the bac+slash is ignored and the following character is ta+en literally. So theway to code the bac+slash is by writing a pair of bac+slashes and the way tocode an apostrophe or a Fuote is by writing 53or5 respectively.