2. freebasic

Upload: mustafa-liqa-madiq-iv-azoulaye

Post on 07-Aug-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/20/2019 2. FreeBASIC

    1/255

    A Beginner’s Guide to FreeBasic

    Richard D. Clark

    Ebben Feagan

    A Clark Productions / HMCso t Book

  • 8/20/2019 2. FreeBASIC

    2/255

    Copyright (c) Ebben Feagan and Richard Clark. Permission is granted to copy, distribute and/or modify this document under the terms of the !" Free #ocumentation $icense, %ersion &.' or any later ersion published by the Free oft*are Foundation+ *ith no n ariant ections, no Front-Co er e ts, and no 0ack-Co er e ts. 1 copy of the license is included in the section entitled 2 !" Free #ocumentation $icense2.

    he source code *as compiled under ersion .&3b of the Free0asic compiler and testedunder 4indo*s '555 Professional and "buntu $inu 6.56. $ater compiler ersions mayre7uire changes to the source code to compile successfully and results may differ underdifferent operating systems. 1ll source code is released under ersion ' of the nu Public$icense (http8//***.gnu.org/copyleft/gpl.html). he source code is pro ided 1 ,4 9:" 1!; 41RR1! ;+ *ithout e en the implied *arranty of

  • 8/20/2019 2. FreeBASIC

    3/255

    o all the members of the Free0asic community, especially the de elopers.

    "

  • 8/20/2019 2. FreeBASIC

    4/255

    Ackno#ledg$ents4riting a book is difficult business, especially a book on programming. t is

    impossible to kno* ho* to do e erything in a particular language, and e eryone learnssomething from the programming community. ha e learned a multitude of things fromthe Free0asic community and *ant to send my thanks to all of those *ho ha e takenthe time to post ans*ers and e amples to 7uestions.

    *ould also like to say a big thanks to the de elopers of Free0asic. 4ithout yourcontinual hard *ork in de elopment, *e *ouldn@t ha e *hat consider the premier :pen

    ource 01 C language for today. he P#F ersion of this book *as created "sing :pen :ffice '.5.',

    http8//***.openoffice.org/.

    %

  • 8/20/2019 2. FreeBASIC

    5/255

    About the Book F0eginner is a concise, hands-on beginner@s guide to Free0asic and is aimed at the

    no ice programmer. he book assumes no prior programming kno*ledge. he goal of thebook is to create a solid foundation in the basics of programming in Free0asic that theprogrammer can build and e pand upon.

    Free0asic is a cross-platform compiler, ho*e er this book concentrates on usingFree0asic under the A'-bit

  • 8/20/2019 2. FreeBASIC

    6/255

    Con'entions (sed in the Book he arious styles used in the book along *ith their meaning, are listed belo*. he

    basic paragraph format is the font you see here *ith each paragraph indented.

    nformation that is supplemental to the topic being discussed *ill be presented in

    the format belo*.

    hese colored bo es ha e additional, supplemental or historical information associated*ith the current topic being discussed.

    ource code is listed in a fi ed font *ith borders to delimit the code segment. ;oushould al*ays type in the programs.

  • 8/20/2019 2. FreeBASIC

    7/255

    Table of Contents

    * A Brie ntroduction to FreeBA0 C..............................................................*%

    # FFERE!CE FR:< > " CD 01 C...............................................................................................&D E; FE1 "RE :F FREE01 C..................................................................................................&

    ! 1u$eric Data 23-es..................................................................................*4

    !E# %ER " " ! !E# # 1 1 ;PE ........................................................................................&G 9E F$:1 ! P : ! # 1 1 ;PE ................................................................................................&HP: ! ER # 1 1 ;PE ..............................................................................................................&H! "

  • 8/20/2019 2. FreeBASIC

    8/255

    9E # EC$1R1 :! 1 E

  • 8/20/2019 2. FreeBASIC

    9/255

    P: ! ER F"!C :! ...............................................................................................................G'"0R:" !E 1!# F"!C :! P : ! ER ...........................................................................................GA

    CRE1 ! 1 C1$$01CD F"!C :! ................................................................................................GP: ! ER : P : ! ER ..............................................................................................................GH1 $ ::D 1 9E1# ....................................................................................................................H'

    5 0tring Data 23-es.....................................................................................5"

    # ;!1< C R ! ............................................................................................................ ......HF IE# $E! 9 R ! ...........................................................................................................H6M R ! ................................................................................................................ ............H34 R ! ...........................................................................................................................HH

    R ! F"!C :! .................................................................................................................HH$E! %ER " ME:F.............................................................................................................&5&" ! R ! F"!C :! 4 9 M R ! P : ! ER .........................................................................&5A

    9E

  • 8/20/2019 2. FreeBASIC

    10/255

    ** 03$bolic Constants...............................................................................*%&

    K# EF !E 1 1 C :! 1! .......................................................................................................& 9E C :! D E;4:R# ...........................................................................................................& 6C:! %ER " K# EF !E.......................................................................................................& 6E!"

  • 8/20/2019 2. FreeBASIC

    11/255

    &ime6alue Function...................................................................................................*+

    7ear Function............................................................................................................*+

    -ee,day Function.....................................................................................................*+

    -ee,DayName Function...........................................................................................*+*

    1 $ ::D 1 9E1# ..................................................................................................................&H&

    *% 2he For$at Function.............................................................................*5!

    R ! F:R

  • 8/20/2019 2. FreeBASIC

    12/255

    9E E$EC C1 E 1 E

  • 8/20/2019 2. FreeBASIC

    13/255

    f *e look at the fact, *e shall find that the great in entions of the age are not, *ith us atleast, al*ays produced in uni ersities.

    Charles Babbage

    *"

  • 8/20/2019 2. FreeBASIC

    14/255

    * A Brie ntroduction to FreeBA0 CFree01 C is a A'-bit 01 C compiler that outputs nati e code for uickbasic Compatibility isFree01 C s call to fame, for it is the most compatible compiler a ailable.

    Di erences ro$ :uickBA0 C● De ault ;DEFuick01 C8 &6-bit

    ● Function calling● Free01 C8 1ll functions must ha e been declared, e en *ith C1$$.● >uick01 C8 4ith C1$$ it is possible to in oke prototype-less functions.

    ● Arra3s not declared● Free01 C8 1ll functions must be e plicitly declared.● >uick01 C8 1rrays are automagically created *ith up to &5 inde es.

    ● @ariables #ith the sa$e na$es as ke3#ords● Free01 C8 !ot allo*ed, e en *ith suffi es.● >uick01 C8 1llo*ed if no suffi is used (ie, dim $EF as integer).

    ● Align$ent / Padding o 2 PE ields● Free01 C8 ame as in C, use F E$#Qconstant to change.● >uick01 C8 !e er done.

    ● Fi8ed )ength strings● Free01 C8 Real length is the gi en len plus one (null char), e en on ;PE

    fields. trings are filled *ith nulls, so strings can t contain null characters.● >uick01 C8 trings are filled *ith *hitespaces.

    *%

  • 8/20/2019 2. FreeBASIC

    15/255

    e3 Features o FreeBA0 C● Built in Gra-hics librar3

    ● Completely compatible *ith old >0 raphics commands, but it builds on thisto offer much more.

    ● upport for high resolutions and any color depth, and any number ofoffscreen pages.● 1ll dra*ing functions can operate on screen as *ell as on offscreen surfaces

    ( E /P" buffers) of any si e.● 1d anced sprites handling, *ith clipping, transparency, alpha and custom

    blending.● #irect access to screen memory.● 0

  • 8/20/2019 2. FreeBASIC

    16/255

    ● nline Asse$bl3● ntel synta .● Reference ariables directly by name *ith no 2trick code2 needed.

    ● Most o the kno#n C libraries can be used directl3 #ithout #ra--ers● DS '.58 cross-platform " oolkit (o er &

  • 8/20/2019 2. FreeBASIC

    17/255

    ● (nli$ited nu$ber o s3$bols● 0eing a A'-bit application, Free01 C can compile source code files up to '

    0 long.● he number of symbols ( ariables, constants, et cetera) is only limited by

    the total memory a ailable during compile time. ;ou can, for e ample,include :pen $, #$, 01 , and D simultaneously in your source code.

    *6

  • 8/20/2019 2. FreeBASIC

    18/255

    ! 1u$eric Data 23-es4hen starting out *ith a ne* programming language, one of the first things you

    should learn is the language@s data types. %irtually e ery program manipulates data, and

    to correctly manipulate that data you must thoroughly understand the a ailable datatypes. #ata type errors rank second to synta errors but they are a lot more troublesome. he compiler can catch synta errors and some data type errors, but most data typeerrors occur *hen the program is running, and often only *hen using certain types ofdata. hese kind of intermittent errors are difficult to find and difficult to fi . Dno*ing thekind, si e and limits of the data types *ill help keep these kinds of errors to a minimum.

    Free0asic has all the standard numeric data types that you *ould e pect for a0asic compiler, as *ell as pointers *hich you usually only find in lo*er-le el languagessuch as C. able A.& lists all the numeric data types that Free0asic supports. n the listbelo*, you *ill notice that nteger and $ong are grouped together. his is because a $ongis ust an alias for nteger. hey are e actly the same data type.

    1u$eric Data 23-es 0i?e )i$its

    0yte G-bit signed, & byte -&'G to &'3

    #ouble 6 -bit, floating point, Gbytes

    -'.'E-A5G to S&.3ESA5G

    nteger ($ong) A'-bit, signed, bytes -',& 3, GA,6 G to',& 3, GA,6 3

    $ong nt 6 -bit, signed, G bytes -H,''A,A3',5A6,G 33 G5Gto H,''A

    A3',5A6,G ,33 ,G53

    hort &6-bit, signed, ' bytes -A',36G to A',363ingle A'-bit, floating point,

    bytes&.& E-AG to A. A ESAG

    "0yte G-bit, unsigned, & byte 5 to '" nteger A'-bit, unsigned , bytes 5 to ,'H ,H63,'H

    "$ong nt 6 -bit, unsigned, G bytes 5 to&G, 6,3 ,53A,35H, &,6&

    "short &6-bit, unsigned, ' bytes 5 to 6 A6

    Pointer A'-bit, memory address, bytes

  • 8/20/2019 2. FreeBASIC

    19/255

    than their signed counterparts. f your data *ill ne er be negati e, using the unsigneddata types *ill allo* you to store larger numbers in the same si e ariable.

    2he Floating Point Data 23-e he floating point data types, ingle and #ouble are able to store numbers *ith

    decimal digits. Deep in mind that floating-point numbers are sub ect to rounding errors,*hich can accumulate o er long calculations. ;ou should carry more than the number ofdecimal digits than you need to ensure the greatest accuracy.

    Pointer Data 23-esPointer data types are unlike the other data types in that they store a memory

    address and not data. ince pointers are handled differently than regular data types, aseparate chapter has been de oted to the sub ect and *ill not be e amined in thischapter.

    1u$eric @ariables

    he numeric data types define *hat numbers you can *ork *ith in your program,but you must create ariables to actually hold the numbers. 1 ariable is a namecomposed of letters, numbers or the underscore character such as

  • 8/20/2019 2. FreeBASIC

    20/255

    he term WbugX for a soft*are error has a long, and some*hat disputed history. heterm predates modern computers and *as used to describe industrial or electricaldefects. ts use in relation to soft*are errors is credited to race 9opper, a pioneer inthe field of soft*are design. 1ccording to the story, a moth *as disco ered bet*een t*oelectrical relays in a

  • 8/20/2019 2. FreeBASIC

    21/255

    0tatic @ariablestatic ariables are used *ithin subroutines and functions and retain their alues

    bet*een calls to the subroutine or functions. he follo*ing program demonstrates using astatic ariable as a counter *ithin a subroutine.

    12

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    Sub StaticSub() 'Dimension a static variable

    Static cnt As Integer

    'Increment the count

    cnt += 1

    Print "In StaticSub";cnt;" time(s)."

    End Sub

    'Dimension working variable

    Dim i As Integer

    'Call sub 10 times

    For i = 1 To 10

    StaticSub

    Next

    Sleep

    End

    )isting !.*+ static.bas

    Analysis n line & the subroutine tatic ub is defined. 1 subroutine is code that ise ecuted only *hen called by the subroutine name *hich, in this case, is tatic ub. $ineA dimensions a static ariable cnt, *hich is incremented *hen the subroutine is called inline 6. $ine 3 prints out the current alue of cnt to the console screen.

    n line &5 a *orking arible that *ill be used in the For-!e t is declared. $ines &through &6 define the For-!e t loop *hich *ill call tatic ub &5 times. $ine &G *aits for akey press and line &H ends the program.

    Running the program in F0 de, you should get the follo*ing output.

    In StaticSub 1 time(s).

    In StaticSub 2 time(s).

    In StaticSub 3 time(s).

    In StaticSub 4 time(s).

    !*

  • 8/20/2019 2. FreeBASIC

    22/255

    In StaticSub 5 time(s).

    In StaticSub 6 time(s).

    In StaticSub 7 time(s).

    In StaticSub 8 time(s).

    In StaticSub 9 time(s).

    In StaticSub 10 time(s).

    ,ut-ut !.*+ ,ut-ut o static.bas

    1s you can see from the output, the alue of cnt is preser ed bet*een calls to thesubroutine. tatic ariables can only be defined *ithin a subroutine or function. %ariablesdeclared outside of a subroutine or function, that is at the module le el, *ill maintaintheir alues and are static by default.

    Co$$on @ariables

    %ariables declared as Common can be shared bet*een multiple code modules, thatis bet*een multiple bas files in the same program. Common ariables *ill be discussed indetail later in this book.

    E8tern and $-ort @ariablesE tern and mport are used *hen creating #$$ s and like Common, are designed to

    share ariables in different modules. E tern and mport *ill be discussed in detail in thechapter on creating #$$s *ith Free0asic.

    Data 23-e 0u i8es ;ou can use >uick0asic style data type suffi es in Free0asic, although this feature

    *as implemented mainly to support >uick0asic legacy code and is only a ailable *hencompiling *ith the W-lang 7bX or W-lang deprecatedX compiler options. able A.' lists thedata type suffi es.

    Data 23-e 0u i8

    0yte b

    hort s

    nteger Y

    $ong Z, l

    "long ul$ong nt ll

    "long nt ull

    ingle U

    #ouble K

    tring [

    2able !.!+ 0u--orted Data 23-e 0u i8es!!

  • 8/20/2019 2. FreeBASIC

    23/255

    Changing 2he De ault Data 23-e1s already mentioned, the default data type for an undeclared ariable is an

    integer. he default data type can be changed for a range of ariables by using one ofthe #EF statements. able A.A lists all the #EF statements a ailable in Free0asic.

    0tate$ent Co$$ent

    #EF0; E a-b ets the default data type to byte forundeclared ariables starting *ith letterrange.

    #EF#0$ a-b ets the default data type to double forundeclared ariables starting *ith letterrange.

    #EF ! a-b ets the default data type to integer forundeclared ariables starting *ith letterrange.

    #EF$! a-b ets the default data type to long forundeclared ariables starting *ith letterrange.

    #EF$! ! a-b ets the default data type to longint forundeclared ariables starting *ith letterrange.

    #EF 9:R a-b ets the default data type to short forundeclared ariables starting *ith letterrange.

    #EF ! a-b ets the default data type to single forundeclared ariables starting *ith letterrange.

    #EF R a-b ets the default data type to string forundeclared ariables starting *ith letterrange.

    #EF"0; E a-b ets the default data type to ubyte forundeclared ariables starting *ith letterrange.

    #EF" ! a-b ets the default data type to uintegerfor undeclared ariables starting *ithletter range.

    #EF"$! ! a-b ets the default data type to ulongint forundeclared ariables starting *ith letterrange.

    #EF" 9:R a-b ets the default data type to ushort forundeclared ariables starting *ith letterrange.

    2able !."+ FreeBasic DEF 0tate$ents

    !"

  • 8/20/2019 2. FreeBASIC

    24/255

    he #EF statement *ill affect all ariables that start *ith a letter in the gi enrange. o if you add #EF#0$ m-n to your program, any ariable starting *ith m or n, *illdefault to a double-type. 1ll other ariables that start *ith different numbers *ill defaultto an integer-type. 1 #im statement *ill o erride any #EF statement, so if you declare aninteger ariable starting *ith m, it *ill be an integer, e en though the #EF#0$ is ineffect.

    (sing Di erent 1u$ber For$ats0esides decimal numbers, Free0asic is able to recogni e numbers in he adecimal,

    binary and octal formats. able A. lists the number base and format to use.

    1u$ber Base For$at

    #ecimal my%ar Q '

    9e adecimal my%ar Q Z9FE0inary my%ar Q Z0&&&&&&&5

    :ctal my%ar Q Z:A36

    E ponential !umbers my%ar Q ' AE&5

    2able !.%+ For$at o 1u$ber Bases

    He8adeci$al 1u$bers

    9e adecimal is a base &6 numbering scheme and ha e digits in the range of 5 to F.9e adecimal numbers are commonly used as constant alues in the 4indo*s 1P andmany third party libraries as it is a compact *ay to represent a large alue. o indicate ahe adecimal number, use the Z9 prefi .

    Binar3 1u$bers0inary is a base ' numbering scheme and ha e digits in the range of 5 and &.

    0inary is the language of the computer. 1lthough *e can enter numbers and letters intothe computer, it all must be translated into binary before the computer can understandit. o indicate a binary number, use the Z0 prefi .

    ,ctal 1u$bers

    :ctal is a base eight numbering scheme and ha e digits in the range of 5 to 3.:ctal numbers *ere ery popular in early computer systems, but aren@t used much todaye cept in some speciali ed applications. o indicate an octal number, use the Z: prefi .

    E8-onential 1u$bers ;ou can use e ponential numbers in your program by adding the E suffi follo*ed

    by the po*er. o use the number &5 , you *ould *rite the number as &5E5 . ;ou candirectly set a double or single type ariable using the e ponent format. ;ou can also usenegati e e ponents such as &5E- , *hich *hen printed to the screen *ould like 1.e-004 .

    !%

  • 8/20/2019 2. FreeBASIC

    25/255

    9hich Data 23-e 2o (se here are a number of different data types a ailable, so ho* do you choose the

    right data type for any gi en applicationJ he rule of thumb is to use the largest datatype you need to hold the e pected range of alues. his may seem like stating theob ious, but many programs fail because the programmer did not fully understand therange of data in their program. 4hen you crate a program, you should map out not onlythe logic of the program, but the data associated *ith each block of logic. 4hen you mapout the data ahead of time, you are less likely to run into data-type errors.

    For e ample, if you *ere *orking *ith 1 C codes, *hich range from 5 to ' , anubyte *ould be a good choice since the range of an ubyte is the same as the range of1 C codes, and you are only using & byte of memory. here is another considerationthough, the WnaturalX data si e of the computer. :n a A'-bit system, the natural data si eis bytes, or an integer. his means that the computer is optimi ed to handle an integer,and does so more efficiently, e en though you are W*astingX A bytes of memory by usingan integer for an 1 C code.

    n most cases an integer is a good general-purpose choice for integer data. herange is 7uite large, it handles both negati e and positi e numbers and you benefit from

    using the computer@s natural data type. For floating point data, a double is a good choicesince, like the integer, it has a good range of alues and better precision than a single.For large integer data you should use a uinteger for positi e data or a longint for largenegati e and positi e numbers. hese are only suggestions+ *hat data type you end upusing *ill be dictated by the needs of your program.

    hese Wrules of thumbX apply to single ariable declarations *here a fe* *asted bytesare not critical. 9o*e er, as you *ill see in the chapter on arrays, choosing the rightsi ed data type is critical in large arrays *here a fe* *asted bytes can add up to alarge amount of *asted memory.

    ,-tion E8-licit ;ou may notice *hen looking at other people s source code, the compiler directi e

    :ption E plicit has been used at the top of each program. 1 compiler directi e is codethat instructs the compiler to do something. n the case of :ption E plicit, it instructs thecompiler to make sure that any ariable being used has been properly #im@ed. 1lthoughyou can *rite a program *ithout using :ption E plicit and e plicitly #im@ing each

    ariable, you run the risk of introducing nasty, hard-to-find bugs as the follo*ing shortprogram illustrates.

    1

    23

    4

    5

    6

    7

    8

    Dim myInteger as Integer

    'set myInteger to a valuemyInteger = 5

    'Oops we mispelled the variable name

    Print "The output of myInteger is";myIntger

    'wait for a keypress

    Sleep

    End

    )isting !.!+ noo-tione8-licit.bas

    !&

  • 8/20/2019 2. FreeBASIC

    26/255

    Analysis n line & my nteger is being declared to the compiler. he compiler *illuse this declaration to allocate space for the ariable. n line A the ariable is beinginitiali ed to a alue, in this case A. he Print statement in line *ill print out the resultto the console screen. leep, listed in line 3, *ill *ait for a keypress and the End key*ordin line G *ill end the program. he End statement isn t mandatory at the end of aprogram but should be used especially if you *ant to return an e it code to the operating

    system.

    1fter typing this program into F0 de and running the program, you should see thefollo*ing output.

    The output of myInteger is 0

    ,ut-ut !.!+ noo-tione8-licit.bas

    he output should be , but as you can see, the result isn@t *hat *as e pected or*anted. ince :ption E plicit *asn@t used in the program, the compiler created a ne*

    ariable *hen it encountered the misspelled ariable name, my ntger, in the printstatement. f this *as large and complicated program, you can see ho* difficult it *ouldbe to track this error do*n and fi it.

    !o*, add :ption E plicit at the top of the program and run it again. ;ou should seethe follo*ing error message in the results pane of F0 de.

    Variable not declared, found: 'myIntger'

    Print "The output of myInteger is";myIntger

    ^

    ,ut-ut !."+ Modi ied noo-tione8-licit.bas

    9ere the compiler detected the misspelled ariable name and informed us of theproblem. ;ou should al*ays use :ption E plicit in your programs. 1 fe* seconds of e tratyping *ill sa e you hours of frustration.

    A 1ote about ,-tion E8-licitRecent ersions of the Free01 C compiler do not allo* :P :! commands

    including :P :! EIP$ C . From no* on :P :! EIP$ C is implied and your programs*ill beha e as if you used :P :! EIP$ C . t is a good rule of thumb to al*ays implicitlydeclare your ariables, so get in the habit no*. o compile a source file that uses :P :!EIP$ C , either use W-lang deprecatedX or remo e the :P :! EIP$ C line from thesource file.

    A )ook Ahead4hen *orking *ith numeric data, there are times *hen it becomes necessary to

    con ert one data type to another. Free0asic offers t*o con ersion methods, implicit ande plicit, *hich you *ill see in the ne t chapter.

    !

  • 8/20/2019 2. FreeBASIC

    27/255

    E8cercises

    &) 4hat data type *ould be the best to store the number &H6J

    ') 4hat data type *ould be the best to store the number '.&A J

    A) 4hat data type is the best for general usage on A'-bit systemsJ

    ) 4hat is the difference bet*een signed and unsigned data typesJ

    ) 4hat prefi *ould you use to designate a binary numberJ

    6) 4hat prefi *ould you use to designate a he idecimal numberJ

    3) 4hat 1lphabetic letters are allo*ed in a he idecimal numberJ

    G) 4hat *ould the he idecimal number &1F be in decimal formJ

    !6

  • 8/20/2019 2. FreeBASIC

    28/255

    " Con'erting 1u$eric Data 23-es4hen you *ork *ith numbers there *ill come a time *hen you *ill need to con ert

    a ariable from one data type to another data type. n Free0asic there are t*o types of

    data con ersion. mplicit, *here the compiler *ill automatically con ert the data typesduring an assignment or calculation, and e plicit using one of the predefined con ersionfunctions.

    $-licit Data Con'ersionmplicit data con ersion occurs either through an assignment statement, or as the

    result of a calculation. 4here implicit data con ersion can cause a problem is in the lossof precision that can result *hen con erting a large data type to a smaller data type.4hile implicit data con ersion eases the programming process some*hat, you *ant tomake sure that the results you are getting are *hat you e pect. ;ou should al*ays checkthe result of an implicit con ersion to make sure the range of alues being con erted is in

    the e pected range. he follo*ing short program illustrates the con ersion that takes place during an

    assignment statement.

    1

    2

    3

    4

    5

    6

    78

    9

    10

    Dim As Double myDbl

    Dim As Integer myInt

    'Set myDbl to a float value

    myDbl = 5.56

    'Assign myInt the float, will be converted to int

    myInt = myDbl

    Print "myInt ="; myIntSleep

    End

    )isting ".*+ assigncon'.bas

    Analysis n lines & and ' t*o ariable are being declared, my#bl, a double-typearibale and my nt, an integer-type ariable. $ine A is a comment *hich, as you can see,

    starts *ith the (single 7uote) character. n line the double-type ariable is beinginitiali ed to the floating-point alue . 6. n line 6 the double is being assigned to aninteger ariable, in oking the implicit con ersion. n line 3 the Print displays the result onthe console *indo*. n line G the program *aits for a key press *ith the leep statementand in line H the End statement is used to end the program.

    Running the program *ill result in the follo*ing output.

    myInt = 6

    ,ut-ut ".*+ assigncon'.bas

    !4

  • 8/20/2019 2. FreeBASIC

    29/255

    n the program, the alue of my#bl *hich is a double-type ariable, *as set to. 6. 4hen my nt *as assigned this float alue, the compiler con erted the alue to an

    integer, and then rounded it up to 6.

  • 8/20/2019 2. FreeBASIC

    30/255

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    Dim As Double myDbl1, myDbl2

    Dim As Integer myInt

    'Assign values to myInt1, myInt2

    myDbl1 = 5.6

    myDbl2 = 3.1

    myInt = myDbl1 / myDbl2

    Print "myInt ="; myInt

    Sleep

    End

    )isting "."+ calccon'!.bas

    Analysis his program is similar to the program in $isting .' e cept thecon ersion process is from t*o double-type ariables to an integer. $ines & and ' declarethe *orking ariables. $ines and set the alues of the t*o double-type ariables. nline 6 the double-type di ision result is implicitly con erted to an integer, resulting inprecision loss. $ine 3 prints the result to the console *indo* and lines G and H *ait for akey press and end the program.

    he output of the program8

    myInt = 2

    ,ut-ut "."+ calcon'!.bas

    n this e ample, the t*o double-type ariables *ere con erted to integers andthen the di ision operation *as performed. ince .6 *as rounded up to 6 during thecon ersion, the result is ' rather than &. his may not be a problem, but you should bea*are that these types of con ersions occur *hen *orking *ith mi ed precision types.

    E8-licit Data Con'ersion here is an alternati e to implicit data con ersion, e plicit data con ersion *here

    you use one of Free0asic@s built-in con ersion functions. ince these functions aredesigned for con ersion, they return consistent results and are unlikely to change e en ifthe implicit rules of the compiler change. E en though it is more *ork, it is al*ays saferto e plicitly con ert data to the needed data type before carrying out operations on thatdata.

    1u$eric Data Con'ersion Functions

    able .& lists all the con ersion functions. Deep in mind that these functions donot check for o erflo*, so be sure that the alue passed to these functions is in thee pected range.

    "7

  • 8/20/2019 2. FreeBASIC

    31/255

    Function 03nta8 Pur-ose Co$$ent

    Cast 0 Q Cast(datatype,e pression)

    Con erte pression todata-type listed.

    #atatype is any of thea ailable Free0asic data-types. E pression is anumeric alue, ariable ore pression.

    C0yte 0 QC0yte(e pression)

    Con erte pression tobyte.

    E pression must be in therange \&'G to &'3.

    C#bl 0 Q C#bl(e pression) Con erte pression todouble.

    E pression must be in therange of -'.'E-A5G toS&.3ESA5G.

    Cint 0 Q Cint(e pression) Con erte pression tointeger.

    E pression must be in therange of \',& 3, GA,6 G to',& 3, GA,6 3.

    C$ng 0 Q C$ng(e pression) Con erte pression tolong. $ong is analias for integer.

    E pression must be in therange of \',& 3, GA,6 G to',& 3, GA,6 3.

    Clng nt 0 QClng nt(e pression)

    Con erte pression tolong int.

    E pression must be in therange of \H,''A,A3',5A6,G ,33 ,G5GtoH,''A,A3',5A6,G ,33 ,G53

    C hort 0 QC hort(e pression)

    Con erte pression toshort.

    E pression must be in therange of -A'36G to A'363.

    C"0yte 0 QC"0yte(e pression)

    Con erte pression tounsigned byte.

    E pression must be in therange of 5 to ' .

    C" nt 0 Q C" nt(e pression) Con erte pression tounsigned integer.

    E pression must be in therange of 5 to ,'H ,H63,'H6.

    C"$ng nt 0 QC"$ng nt(e pression)

    Con erte pression tolong unsignedinteger.

    E pression must be in therange of 5 to&G, 6,3 ,53A,35H, &,6&.

    C" hort 0 QC" hort(e pression) Con erte pression tounsigned short.

    E pression must be in therange of 5 to 6 A .

    C ng 0 Q Cng(e pression) Con erte pression tosingle.

    E pression must be in therange of &.& E-AG to A. AESAG.

    2able ".*+ FreeBasic Con'ersion Functions

    "*

  • 8/20/2019 2. FreeBASIC

    32/255

    4hen e amining con ersion functions it is important to understand ho* thefunction rounds *ith both negati e and positi e numbers. he Free0asic con ersionfunctions round numbers up, making positi e number more positi e and negati enumbers more negati e. he follo*ing program illustrates the rounding *ith Cast andCint, as *ell as demonstrating that the con ersion functions *ill *ork *ith e pressions as*ell as numbers.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    Dim as Double myDouble1, myDouble2, myDouble3

    Dim as Integer myInt

    'Set variable ranges

    myDouble1 = 143.5

    myDouble3 = 143.4

    myDouble2 = -143.5

    myInt = 12

    'Show cast in action

    Print "** Cast **"

    Print "Double1 ";myDouble1;" cast to integer ";Cast(Integer, myDouble1)

    Print "Double2 ";myDouble2;" cast to integer ";Cast(Integer, myDouble2)

    Print "Double3 ";myDouble3;" cast to integer ";Cast(Integer, myDouble3)

    Print "Expression ";myDouble1;" + ";myInt;" cast to double ";

    Print Cast(Double, myDouble1 + myInt)

    Print

    'Show cint in action

    Print "** CInt **"

    Print "Double1 ";myDouble1;" cint to integer ";CInt(myDouble1)

    Print "Double2 ";myDouble2;" cast to integer ";CInt(myDouble2)

    Print "Double3 ";myDouble3;" cast to integer ";CInt(myDouble3)

    Print "Expression ";myDouble1;" + ";myInt;" cast to integer ";CInt(myDouble1 + myInt)

    Print "Expression ";myDouble2;" + ";myInt;" cast to integer ";CInt(myDouble2 + myInt)

    Print

    Sleep

    End

    )isting ".%+ con'ert.bas

    Analysis his program demonstrates the built-in Free0asic con ersion functions.$ines & and ' declare the *orking ariables using the alternate format of the #im. *otables of information are printed to the console in line &' to &G and lines '& to '3. n lines&A to &6, the result of the Cast function is printed directly to the screen, as is the Cintfunction in lines '' to '6. !ormally the alues *ould be sa ed in another ariable to beused in the program. $ine &6 ends *ith a semi-colon. his instructs the compiler not to"!

  • 8/20/2019 2. FreeBASIC

    33/255

    print a carriage return after the print statement, so that *hen the alue of Cast is printedin line &3, the alue *ill appear on the same line as the data printed in line &6. heprogram is closed in the usual *ay using leep and End.

    Running the program *ill produce the output sho*n belo*.

    ** Cast **

    Double1 143.5 cast to integer 144

    Double2 -143.5 cast to integer -144

    Double3 143.4 cast to integer 143

    Expression 143.5 + 12 cast to double 155.5

    ** CInt **

    Double1 143.5 cint to integer 144

    Double2 -143.5 cast to integer -144Double3 143.4 cast to integer 143

    Expression 143.5 + 12 cast to integer 156

    Expression -143.5 + 12 cast to integer –132

    ,ut-ut ".%+ con'ert.bas

    1s you can see from the program, you can use both numbers and e pressions inthe con ersion functions. Deep in mind that if you pass an e pression to a con ersionfunction, the e aluated e pression must not e ceed the limit of the target data type, or

    an o erflo* *ill occur. $ooking at the output you can see that the rounding for middlealues is up or greater in magnitude. & A. rounds up, making the resulting number morepositi e and \& A. , more negati e.

    (sing Con'ersion Functions in Macros

    :ne area *here the con ersion functions listed in able .& are useful is in thecreation of macros. 1 macro is a small piece of e ecutable code that the compiler insertsinto the program at designated areas.

  • 8/20/2019 2. FreeBASIC

    34/255

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    2627

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    'Macro created by v1ctor

    #define MAKDWORD(x,y) (cint(x) shl 16 or cint(y))

    Dim myInt As Uinteger

    Dim As Integer i, cnt

    'Store row 5 column 5 in a single uinteger

    myInt = MAKDWORD(5, 5)

    'Set the width and height of the console window

    Width 80, 25

    'Print column headers

    cnt = 1

    For i = 1 To 80

    'Print columns as 12345678901...

    If cnt = 10 Then

    cnt = 0

    End If

    Locate 1, i

    'Convert to string so we don't get leading space

    Print Str(cnt)

    'Increment our counter

    cnt += 1

    Next

    'Print row headers

    cnt = 2For i = 2 To 25

    'Row numbers will be like col numbers

    If cnt = 10 Then

    cnt = 0

    End If

    Locate i, 1

    'Convert to string so we don't get leading space

    'We need the semi-colon so a line feed isn't printed

    'on line 25 which would scroll screen.

    Print Str(cnt);

    'Increment our counter

    cnt += 1

    Next

    'Print out string on saved location

    Locate Hiword(myInt), Loword(myInt)

    Print "We stored the screen location in a single uinteger!"

    "%

  • 8/20/2019 2. FreeBASIC

    35/255

    45

    46

    47

    48

    Sleep

    End

    )isting ".&+ $akd#ord.bas

    Analysis n line ' the Kdefine compiler directi e is used to create a macro. 1macro is an snippet of e ecutable code that the compiler *ill insert into the code *hen itfinds the macro name,

  • 8/20/2019 2. FreeBASIC

    36/255

    9

    0

    1

    2

    3

    4

    5

    6

    7

    8

    9

    0

    ,ut-ut ".&+ $akd#ord.bas

    K#efine is fully e plored in the chapter on symbolic constants later in the book.

    Deci$al Rounding Functions

    Free0asic has t*o built-in rounding functions for use *ith decimal numbers. able.' lists the functions along *ith their e planations.

    Function 03nta8 Co$$ent

    nt 0 Q nt(e pression) Returns an integer alue less than or e7ual tothe input.

    Fi 0 Q Fi (e pression) Returns the integer part of the input.

    2able ".!+ FreeBasic Rounding Functions

    1s *ith the other con ersion functions, this should be tested *ith both negati eand positi e numbers to see ho* the function beha es. he program intfi .bas listedbelo* illustrates the results returned by the functions as *ell as their use *ithcalculations.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    'Create some double variables

    Dim As Double myDouble1 = -5.5, myDouble2 = 5.9

    'Show rounding on negative and positive values

    Print "Doubles:", myDouble1, myDouble2

    Print "Int:", Int(myDouble1), Int(myDouble2)

    Print "Fix:", Fix(myDouble1), Fix(myDouble2)

    Print

    'Try some calculation expressions

    myDouble1 = -15.78

    myDouble2 = 22.12

    Print "Expression:",myDouble1;" +";myDouble2;" = "; Str(myDouble1 + myDouble2)

    "

  • 8/20/2019 2. FreeBASIC

    37/255

    12

    13

    14

    15

    16

    17

    18

    Print "Int:", Int(myDouble1 + myDouble2)

    Print "Fix:", Fix(myDouble1 + myDouble2)

    'Wait for keypress

    Sleep

    End

    )isting ". + int i8.bas

    Analysis $ine ' uses the alternati e synta for #im to declare and initiali e the*orking ariables. $ine through 6 display the results of the con ersion function suingboth positi e and negati e numbers. $ine H and &5 set the alues for the ariables to beused in calculations. $ines &' through & display the results of the con ersion functionsusing calculations so Free0asic resol es the calculations before in oking the functions.$ines &3 and &G end the program in the usual *ay.

    he result of running the program is sho*n in :utput .6.

    Doubles: -5.5 5.9

    Int: -6 5

    Fix: -5 5

    Expression: -15.78 + 22.12 = 6.34

    Int: 6

    Fix: 6

    ,ut-ut ". + in i8.bas

    !otice that in the output nt returns a \6 for the input \ . , since 6 is less than \. , and for .H since is less than 6. Fi on the other hand truncates the decimal and

    returns the integer portion of the double. 1s you can see both functions *ill also *ork*ith an e pression, in this my#ouble& S my#ouble'. 4hich function you *ould usedepends on *hat beha ior you *ould need *ith negati e numbers, as they both returnsimilar results *ith positi e numbers.

    A )ook Aheadn addition to the built-in con ersion functions, there are a number of functions

    a ailable in the C Runtime $ibrary, *hich is the sub ect of the ne t chapter.

    "6

  • 8/20/2019 2. FreeBASIC

    38/255

    E8ercises&) 9o* do you stop your program from printing a carriage return at the end of a lineJ

    ') 4hat function *ould you use to con ert an unkno*n alue to a #oubleJ

    A) 4hat function *ould you use to con ert an unkno*n alue to an ntegerJ

    ) 4hat *ould be the result of the e7uation / ' if assigned to an ntegerJ

    ) 9o* do the functions nt() and Fi () differ in their resultsJ

    "4

  • 8/20/2019 2. FreeBASIC

    39/255

    % ntroduction to the C Runti$e )ibrar3:ne of the original moti ations for creating Free0asic *as to pro ide an easy-to-

    use *rapper for the C Runtime $ibrary according to 1ndre %ictor, the language creator.

    Free0asic is as ad anced as it is today because many of the functions are *rappers forthe runtime functions, *hich simplified the creation of the language.ince Free0asic uses the C runtime library, you can use it as *ell in your programs,

    and there are a number of ery useful con ersion functions a ailable. he functiondefinitions are contained in the header file crt.bi, and you gain access to those functionsby using the K nclude directi e.

    Caution !ot all the functions listed in the arious bi files in the crt folderha e been implemented in Free0asic. f you get an error similar to the follo*ing]-ath/ ilena$eI.o + ake+;.te8tJ78* c=+ unde ined re erence to Krint> , *here path/filename is yourprogram s path and filename, then the function you are trying to use is not supported.

    his is a linker error and indicates that the linker *as not able to find the referencedfunction. here are also a number of functions and structures that *ill only *ork in4indo*s and some that are !" E tensions and *ill only *ork on $inu .

    2he < nclude Directi'e he synta for the K nclude directi e is < nclude L,nceI ilena$e.e8tN .

    Remember that a compiler directi e instructs the compiler to do something, and in hiscase, it instructs the compiler to include the file Wfilename.e tX *hen compiling. 4hen thecompiler reads this directi e, it stops reading the current file and starts reading theincluded file. f the included file also has an K nclude directi e, then that file is read in as

    *ell. ;ou can ha e up to &6 nested includes per program. o use the runtime con ersionfunctions in your o*n program you *ould add < nclude ,nce crt.biN at the top ofyour program.

    he file e tension bi stands for Wbasic includeX and is usually declarationstatements and/or subroutines and functions. he crt.bi file is located in the inc folder ofyour Free0asic installation. f a bi file is not located in the folder *here the program isbeing compiled, the compiler *ill look in the inc folder for the file. f it can@t find the file, it*ill issue an error. ;ou can also include a path *ith the filename if you keep your includefiles in a common folder besides the inc folder.

    f you look at the contents of crt.bi you see that the file simply includes other filesand references the library that contains the actual function code.

    1

    2

    3

    4

    5

    6

    7

    8

    #ifndef __CRT_BI__

    #define __CRT_BI__

    #ifdef __FB_WIN32__

    # inclib "msvcrt"

    #endif

    #include once "crt/string.bi"

    "5

  • 8/20/2019 2. FreeBASIC

    40/255

    9

    10

    11

    12

    13

    14

    15

    16

    17

    #include once "crt/math.bi"

    #include once "crt/time.bi"

    #include once "crt/wchar.bi"

    #include once "crt/stdlib.bi"

    #include once "crt/stdio.bi"

    #include once "crt/io.bi"

    #include once "crt/errno.bi"

    #endif ' __CRT_BI__

    )isting %.*+ crt.bi

    Analysis Crt.bi contains a number of compiler directi es, the statements that start*ith the K character to control the compilation process. n line the directi e Kifndefmeans Wif not definedX. f the symbol TTCR T0 TT has not already been defined, then line' *ill define the symbol. he Kifdef directi e in line means Wif definedX. f the compiler

    is running on a 4inA' machine, the symbol TTF0T4 !A'TT *ill be defined *hich *illinclude the library 2ms crt2 on line *ith the Kinclib directi e *hich means WincludelibraryX. he Kendif on line 6 closes the opening Kifdef on line . "nder 4indo*s,Free0asic uses the

  • 8/20/2019 2. FreeBASIC

    41/255

    a function, be sure not to change anything in the file. ;ou should al*ays open the files inread-only mode if your editor pro ides that functionality.

    2he Declaration 0tate$entf you look at math.bi you *ill see a number of #eclaration statements. 1

    declaration statement is a function prototype that tells the compiler that there is afunction definition some*here in the program code, or in a library or an e ternal dll. hisor1ard re erence is used so that the compiler *on@t complain if the function or sub is

    called before it finds the actual code for the function. :nce you understand ho* tointerpret a declaration statement, you *ill be able to use any function in the runtimelibrary.

    o understand the components of a declaration statement, here is the declarationstatement for the ceil function in math.bi. he ceil function rounds a decimal alue up tothe nearest integer. hat is, &. *ould become '.

    Declare function ceil cdecl Alias "ceil" (byval as double) as double

    ;ou can break this declare do*n into the follo*ing functional sections.• Declare 8 his is the key*ord for a declare statement.• Function 8 his can either be Function, to indicate that this procedure returns a

    alue, or ub, *hich indicates that the procedure does not return a alue.• Ceil 8 his is the name of the function and the name that you *ould use in your

    code. #o not use the name after 1lias.• Cdecl 8 his is the function s method of passing arguments. 4hen calling an

    e ternal function, parameters must be pushed on the stack in the correct order so

    that the function can pop the parameters off the stack correctly. Cdecl stands for C#eclare, and passes the arguments from right to left using the C con ention ofparameter passing. he Pascal calling con ention pushes arguments from left toright and is used *hen calling functions created in the Pascal language. he0tdcall calling con ention pushes arguments from right to left and is used in 0asiclibraries and 4indo*s 1P .

    • Alias 8 his is an alternate name that is used by the linker *hen your code is linkedto other languages. ;ou use an alias in case there is a function in the targetlanguage that has the same name as your function.

    • ; = 8 he alues inside the parenthesis are the parameters that the function or sube pects. Ceil e pects one parameter, a double-type alue. f the function e pects

    multiple parameters, then commas *ill separate them. 1 parameter can be any ofthe Free0asic data types or a composite type.

  • 8/20/2019 2. FreeBASIC

    42/255

    • As Ldata t3-eI 8 he 1s key*ord after the parameter list indicates the return typeof the function. ubs do not ha e a return type so there isn@t an 1s clause after theparameter list.

    !otice that the ceil function returns a double and not an integer, e en though thecon ersion function rounds off the decimal portion. his is to pre ent integer o erflo* for

    ery large numbers. E en though ceil, and the other runtime con ersion functions returna double you can implicitly con ert them to integers by simply assigning the return to aninteger ariable or using the Cast function. 0e sure to use an integer data type *ith alarge enough range for the result.

    o use Ceil in your program you *ould *rite myDouble = Ceil(aDouble) or myInt =Ceil(aDouble) . 1ll declaration statements follo* the same pattern as Ceil.

    #$$s created *ith %isual 0asic 6 tm and belo* are C:< ob ects and not standard#$$s. n order to use %06 #$$s *ith Free0asic you *ill need to create a C:< interface toaccess the #$$ functions. Creating a C:< interface is a complicated topic and is beyondthe scope of this book.

    Runti$e Con'ersion Functions able .& lists some of the more useful con ersion routines contained *ithin the

    runtime library along *ith he synta and some comments about the function.

    Function 03nta8 Co$$ent

    Ceil 0 Q Ceil(double-typee pression)

    Ceil returns the nearestinteger greater thane pression.

    Floor 0 Q Floor(double-typee pression) Floor returns the nearestinteger less than e pression.

  • 8/20/2019 2. FreeBASIC

    43/255

    calling procedures, so pointers are used instead. here are t*o *ays to pass pointer datato a function+ by e plicitly declaring a pointer data type *hich you *ill see in the chapteron pointers, or by using the 1ddress:f operator *hich is e plained here.

    2he Address, ,-erator O4hen the compiler creates a ariable, it allocates a portion of memory e7ual to the

    si e of the data type. For an integer it *ould allocate bytes and for a double it *ouldallocate G bytes. Each memory location has an address associated *ith it so that the CP"can mo e data into and out of the memory location. 4hen the compiler allocates thememory, the operating system returns an address for the memory location so that thecompiler can access that location. 4hen you are *orking *ith ariables you are actually*orking *ith an addressable memory location in the computer. ;ou don t ha e to *orryabout the address since the compiler handles all those details for you+ you can ust usethe ariable in your program.

    9o*e er, *hen you need to call a function like

  • 8/20/2019 2. FreeBASIC

    44/255

    he follo*ing short program illustrates this concept.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    'Need to include the runtime library

    #include "crt.bi"

    'Set up some variables

    Dim As Double myDouble, FracPart, IntPart

    'Set the value we want to convert

    myDouble = 12.56

    'Call the function. Notice that we are using the addressof

    'operator @ on IntPart.

    FracPart = modf(myDouble, @IntPart)

    'Get the result.

    Print "myDouble = ";myDouble

    Print "Fractional part:";FracPart

    Print "Integer part:";IntPart

    Sleep

    End

    )isting %."+ addresso .bas

    Analysis n line & the crt.bi is included in this program so that all the supportedfunctions *ill be a ailable to the program. n line all of the *orking ariables aredeclared. n line G, the ariable to be operated on is set to a decimal alue. he

  • 8/20/2019 2. FreeBASIC

    45/255

    . 6 is the result of the precision con ersion you *ill get *ith a double alue. Rememberin the pre ious sections it *as mentioned that double and single data types are prone torounding errors. 9ere you see *hy this is true.

    Caution 4hen you are dealing *ith a pointer parameter, you must be sure to passthe correct data type to the parameter. n the case of

  • 8/20/2019 2. FreeBASIC

    46/255

    $ine ' in the program includes the crt.bi *hich is re7uired for using any of theruntime functions. n line the t*o *orking double-type ariables are dimensioned andinitiali ed. 1s you can see, calling the runtime functions is e actly the same as callingany of the Free0asic built-in functions. Running the program *ill produce the follo*ingoutput.

    Ceil with 12.56 returns 13

    Ceil with -12.56 returns -12

    Floor with 12.56 returns 12

    Floor with -12.56 returns -13

    ,ut-ut %.!+ crt unc.bas

    1s you can see in the output, Ceil returns the nearest integer greater than thealue. &A is greater than &' and -&' is less negati e than -&'. 6. Floor does ust theopposite+ it returns the nearest integer less than the alue. &' is less than &'. 6 and -&Ais more negati e than -&'. 6.

    A )ook Ahead!ormally *hen you use numbers in your program, you are going to do some sort of

    calculation *ith them. n the ne t chapter you *ill see Free0asic s arithmetic operators,learn about operator precedence and e plore the bits that make up a number.

    %

  • 8/20/2019 2. FreeBASIC

    47/255

    E8ercises&) 4hat is the e tension of files that normally contain function declarations for

    librariesJ

    ') 4hat is the difference bet*een the Ceil() and Floor() functions in the C runtimelibraryJ

    A) 4hat compiler directi e is used to add additional files before compilationJ

    ) 4hat is a common cause of a egmentation Fault or eneral Protection FaultJ

    %6

  • 8/20/2019 2. FreeBASIC

    48/255

    & Arith$etic ,-eratorsArith$etic ,-erators

    he able 6.& lists all the arithmetic operators in Free0asic. n the table belo*, theoperators *ill *ork on t*o or more e pressions, *here e pression is a number, ariableor another e pression. he s7uare brackets in the synta column indicate optionaladditional e pressions.

    Function 03nta8 Co$$ent

    S (1ddition) 0 Q e pression Se pression ] S e pression^_

    Returns the sum of t*o ormore e pressions.E pression can be anumber, ariable or anothere pression.

    - ( ubtraction) 0 Q e pression \ e pression] - e pression^_

    Returns the differencebet*een t*o or moree pressions.

    N (

  • 8/20/2019 2. FreeBASIC

    49/255

    Function 03nta8 Co$$ent

    e pression the implicit di ision of thee pressions as an integerresult. f e pression is adecimal alue, e pression isrounded before the di ision.

    - (!egation) 0 Q - e pression Returns the negated alueof e pression. his is thesame as multiplying by \&. fe pression is positi e, 0 *illnegati e. f e pression isnegati e, 0 *ill positi e.

    ( ) (Parenthesis) 0 Q e pression operator( e pression ] operator

    e pression ] (^_)

    Forces e aluation ofe pression. Parenthesis canbe nested, but must beclosed properly or a compileerror *ill occur.

    2able &.*+ Arith$etic ,-erators

    ;ou should be familiar *ith most of these operators from math class. ntegerdi ision is used *hen you are not concerned about the remainder of the di ision process.

    he

  • 8/20/2019 2. FreeBASIC

    50/255

    he 9$ and 9R operators *ill be discussed in the ne t section, 0it*ise:perators. hey are included here to sho* *here they fall in the precedence rules.

    $ooking at the table and the e7uation S 6 N A you can see that this *ill e aluateto 'A not AA, since multiplication has a higher precedence then addition. he compiler*ill read the e pression from left to right, pushing alues onto an internal stack until itcan resol e part or all of the e7uation. For this e7uation *ill be read and pushed, then

    the S operator *ill be read and pushed onto the stack. ince the S operator re7uires t*ooperands, the compiler *ill read the ne t element of the e pression *hich *ill be the Noperator. his operator also re7uires t*o operands, so N *ill be pushed onto the stack andthe A *ill be read. ince N takes priority o er S, the 6 and A *ill be multiplied, and that

    alue *ill be stored on the stack. 1t this point there is a , S and &G on the stack. incethere is only one operator left and t*o operands, the and &G *ill be added together tomake 'A, *hich *ill be returned as the result of the e pression.

    f you *anted to make sure that S 6 gets e aluated first, then you *ould useparenthesis to force the e aluation. ;ou *ould *rite the parenthesi ed e pression as ( S6) N A. ince the parenthesis ha e the highest precedence, the e pression they contain*ill be e aluated before the multiplication. he e aluation process here is the same asthe pre ious process. he ( is treated as an operator and is pushed onto the stack. he ,S, and 6 are read follo*ed by the ). he ) signals the end of the parenthesis operation, sothe and 6 are added together and pushed onto the stack. he N is read along *ith the A.

    he stack at this point contains an &&, N and A. he && and A are multiplied together andAA is returned as the result of the e aluation.

    ;ou can also embed parenthesis *ithin parenthesis. Each time the compilerencounters a (, it begins a ne* parenthesis operation. 4hen it encounters a ), the last ( isused to e aluate the items contained *ithin the ( and ) and that result is either placed onthe stack for further e aluation or returned as a result. Each ( must be match to a ) or acompiler error *ill occur.

    he follo*ing program demonstrates both implicit e aluation and forcede aluation.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    Option Explicit

    Dim As Integer myInt

    'Let compiler evaluate expression according to precedence

    myInt = 5 + 6 * 3

    Print "Expression 5 + 6 * 3 = ";myInt

    'Force evaluation

    myInt = (5 + 6) * 3

    Print "Expression (5 + 6) * 3 = ";myInt

    'Wait for keypress

    Sleep

    End

    )isting &.*+ -recedence.bas

    &7

  • 8/20/2019 2. FreeBASIC

    51/255

    Analysis 1s al*ays *e open the program *ith :ption E plicit in line & and declarethe *orking ariables in line A. n line 6 the compiler e aluates the math e pressionaccording to precedence rules and stores the result in my nt, *hich is printed to theconsole *indo* in line 3. n line &5, parenthesis are used to force the e aluation of thee pression *hich is printed to the console screen in line &&. $ines & and & close theprogram in the usual *ay.

    1s you can see from the output belo*, using parenthesis allo*s you to control thee aluation of the e pression.

    Expression 5 + 6 * 3 = 23

    Expression (5 + 6) * 3 = 33

    ,ut-ut &.*+ -recedence.bas

    4hat about the case *here to* operators are used that ha e the sameprecedence le elJ 9o* does Free0asic e aluate the e pressionJ o find out, run thefollo*ing program.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    Option Explicit

    Dim As Integer myInt

    'Expression 1

    myInt = 3 + 5 - 4

    Print "Expression 1: 3 + 5 - 4 is";myInt

    'Expression 2

    myInt = 3 - 5 + 4

    Print "Expression 2: 3 - 5 + 4 is";myInt

    'Expression 3

    myInt = 6 * 2 / 3

    Print "Expression 3: 6 * 2 / 3 is";myInt

    'Expression 4

    myInt = 6 / 2 * 3

    Print "Expression 4: 6 / 2 * 3 is";myInt

    &*

  • 8/20/2019 2. FreeBASIC

    52/255

    26

    27

    Sleep

    End

    )isting &.!+ sa$e-recedence.bas

    Analysis n line A the *orking ariable my nt is declared, since the program usesthe :ption E plicit directi e in line &. n line 6 the e pression has the S operator first andthe \ second, *hile in line && the order has been re ersed to test the e aluation order.

    he results are printed in lines G and &A. $ine &6 and '& use the N and / operators on thesame manner to test the order of e aluation and the results are printed in lines &G and'A.

    Running the program produces the follo*ing result.

    Expression 1: 3 + 5 - 4 is 4

    Expression 2: 3 - 5 + 4 is 2Expression 3: 6 * 2 / 3 is 4

    Expression 4: 6 / 2 * 3 is 9

    ,ut-ut &.!+ ,ut-ut o sa$e-recedence.bas

    1s you can see from the output each e pression has been e aluated from left toright. n e pression &, A S is G and subtracting e7uals . n e pression ', A \ ise7ual to -', and adding e7uals '. n e pression A, 6 N ' is &' and di ide that by A andyou get . n e pression , 6 /' is A and multiplies by A results in H. he program sho*sthat operators that ha e the same precedence le el are e aluated from left to right.

    his is the case *here parenthesis are ery helpful in ensuring that the e aluationorder is according to your program needs. 4hen in doubt, al*ays use parenthesis toensure that the result is *hat you *ant in your program.

    0hortcut Arith$etic ,-eratorsFree0asic has a number of shortcut arithmetic operators similar to those found in

    the C programming language. hese operators ha e the same precedence as their singlecounterparts. he follo*ing table lists the shortcut operators.

    ,-erator 03nta8 Co$$entSQ 0 SQ e pression 1dd 0 to e pression and

    assign to 0.-Q 0 -Q e pression ubtract 0 to e pression

    and assign to 0.

    NQ 0 NQ e pression

  • 8/20/2019 2. FreeBASIC

    53/255

    ,-erator 03nta8 Co$$ent

    assign to 0.

    VQ 0 VQ e pression nteger di ide 0 bye pression and assign to 0.

    2able &."+ 0hortcut Arith$etic ,-erators

    "sing these operators *ill cut do*n on the typing you ha e to do, especially forstatements such as a = a + 1 , *hich can be *ritten as a += 1.

    Binar3 1u$ber 03ste$Computers use the binary, or base ', numbering system to represent data. 0ase '

    digits are the numbers 5 and &. 1 single binary & or 5 is called a bit. Four bits is called anybble. *o nybbles, or G bits is called a byte and ' bytes make up a *ord. he si e of adata type determines ho* many bits are a ailable to represent a particular number. 1byte has G bits, a short has &6 bits, an integer has A' bits and a longint has 6 bits.

    ;ou *ill notice that each data type is double the si e of the pre ious data type. his is because the binary system uses po*ers of ' to represent data. ' 5 is &. ' & is '. ' ' is

    . ' A is G. ' is &6, and so on. o find the alue of a binary number, you start from theright, *hich is position 5 and add the po*er of t*os going left if there is a & in the bitposition. f a nybble is &&5&, then the right-most position is ' 5, the ne t position left isskipped since it has a ero, follo*ed by ' ' and finally ' A. Resol ing the po*er terms gi esyou & S S G *hich e7uals &A. he alue ranges for the different data types is a directresult of the number of bits in each data type.

    0eing able to manipulate indi idual bits, bytes and *ords has a number of uses.For e ample, the messaging system of the 4indo*s 1P use integers to store both the idof a control and e ent the control recei ed, as the follo*ing code snippet sho*s.

    1

    2

    3

    Case WM_COMMAND

    wmId = Loword( wParam )

    wmEvent = Hiword( wParam )

    )isting &."+ 0ni--et ro$ 9indo#s Message )oo-

    n this snippet the id of the control is stored in the lo* *ord of *Param, and thee ent number is stored in the high *ord. ince a *ord is ' bytes or &6 bits, you can store6 A ids in a single *ord, using an unsigned data type, or A'363 ids for a signed datatype. his is a ery efficient *ay to manage data in your program.

    2he 0ign Bit he sign bit, the leftmost bit, is used by the computer to determine if a signed data

    type is negati e or positi e using the *o s Complement form of notation. o represent anegati e number, the positi e alue of the number is negated, that is all the & s arechanged to 5 and the 5 s are changed to & s, and & is added to that result. For e ample,binary is 5555 5&5&. !egating all the bits results in &&&& &5&5. 1dding & results in &&&&&5&&. ince the leftmost bit is &, this is a negati e number.

    &"

  • 8/20/2019 2. FreeBASIC

    54/255

    4e can confirm this by using the po*er of ' notation *hich results in the follo*ing8&'G (' 3) S 6 (' 6) S A' (' ) S &6 (' ) S G (' A) S 5 S ' (' &) S & (' 5) Q - . Remember, if

    a bit is ero, *e add ero to the total. he follo*ing program sho*s the binaryrepresentation of both positi e and negati e fi e.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    1213

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    Option Explicit

    Dim As Byte myByte

    Dim As String myBits

    myByte = 5

    'Get the binary form of number

    myBits = Bin(myByte)

    'Append some leading zeros so print line up

    myBits = String(8 - Len(myBits), "0") & myBits

    'Print out nybbles with a space between so is is easier to read

    Print "myByte =";myByte;" which is binary ";Print Mid(myBits, 1, 4) & " " & Mid(myBits, 5, 4)

    myByte = -5

    'Get the binary form of number

    myBits = Bin(myByte)

    'Append some leading zeros so print line up

    myBits = String(8 - Len(myBits), "0") & myBits

    'Print out nybbles with a space between so is is easier to read

    Print "myByte =";myByte;" which is binary ";

    Print Mid(myBits, 1, 4) & " " & Mid(myBits, 5, 4)

    Sleep

    End

    )isting &.%+ signbit.bas

    Analysis $ines A and declare the *orking ariables, a byte that *ill represent theactual number and a string that *ill represent the binary alue. n line 6 the my0yte isset to . n line G the 0in function is used to return a string that represents the binary

    alue of . ince 0in does not return any leading 5 s, the tring function is used to padthe string to a full G bits for display purposes.

    he first parameter of the tring function is the number of characters to add andthe second parameter is the character to use to pad the string. ince a byte is G bitslong, subtracting the length of my0its from G *ill gi e the number of 5 s to add to thestring, if the length of my0its is less than G. n line &' the numeric alue of my0yte isprinted, *hich is . 1 semi-colon is added to the end of print statement so that Print *illnot print out a carriage return.

    n line &A the binary string is printed in t*o groups of four, that is each nybble, tomake the display easier to read. he

  • 8/20/2019 2. FreeBASIC

    55/255

    string. he first parameter of the

  • 8/20/2019 2. FreeBASIC

    56/255

    Bit#ise ,-erators

    Free0asic includes a number of operators that manipulate the bits of a number. he follo*ing table lists the bit*ise operators in order of their precedence. hat is, the

    first ro* has the highest precedence *hile lo*er ro*s ha e lo*er precedence.

    ,-erator 03nta8 2ruth 2able Co$$ents

    !ot (0it*ise negation) 0 Q !: e pression NOT 0 = 1NOT 1 = 0

    n erts operand bit+turns a & into 5 and a 5into &.

    1nd (0it*isecon unction)

    0 Q e pression 1!#e pression

    0 AND 0 = 01 AND 0 = 00 AND 1 = 01 AND 1 = 1

    Result bit is & only ifboth operand bits are &.

    :r (0it*isedis unction) 0 Q e pression :Re pression0 OR 0 = 01 OR 0 = 10 OR 1 = 11 OR 1 = 1

    Result bit is & if eitheror both operand bits is&.

    Ior (0it*isee clusion)

    0 Q e pression I:Re pression

    0 XOR 0 = 01 XOR 0 = 10 XOR 1 = 11 XOR 1 = 0

    Result bit is & if operandbits are different.

    E7 (0it*isee7ui alence)

    0 Q e pression E>%e pression

    0 EQV 0 = 11 EQV 0 = 00 EQV 1 = 01 EQV 1 = 1

    Result bit is & if bothoperand bits are 5 or &.

    mp (0it*iseimplication)

    0 Q e pression

  • 8/20/2019 2. FreeBASIC

    57/255

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    'Apply NOT operator

    myByte = Not myByte

    'Value after NOT operation

    Print "NOT myByte: ";myByte," Binary: ";Bin(myByte)

    'Add 1 after NOT operation

    myByte = myByte + 1

    'Print result = -5 in decimal and binary

    Print "myByte + 1: ";myByte," Binary: ";Bin(myByte)

    Sleep

    End

    )isting .*+ not.bas

    Analysis n line A the *orking ariable my0yte is declared and initiali ed using thealternate format of the #im statement. $ine 6 prints out the alue of my0yte in both

    decimal and binary. n line G the !: operator is used to negate all the bits in the integer. he result of the operation is printed to the console *indo* in line &5. n line &', & isadded to the result as re7uired by the t*o s complement method. he result of thisoperation id printed in line & . he program is closed in the usual *ay.

    4hen the program is run, you should see the follo*ing output.

    myByte: 5 Binary: 101

    NOT myByte: -6 Binary: 11111010

    myByte + 1: -5 Binary: 11111011

    ,ut-ut .*+ ,ut-ut o not.bas

    1s you can see from the output, the final result of the program is - after applyingthe t*os complement method to my0yte. he & in the leftmost position indicates that thenumber is negati e. 0in doesn t add the leading eros in the first output line, but thethree digits sho*n are the rightmost three digits.

    2he A1D ,-erator he 1!# operator can be used to test if an indi idual bit is & or 5 by using a mask

    alue to test for the bit position as the follo*ing program illustrates.

    1

    2

    3

    4

    5

    6

    Option Explicit

    'Declare working variable and mask value

    'The mask will test the 3rd bit position, i.e. 4

    Dim As Byte myByte = 5, Mask = 4

    &6

  • 8/20/2019 2. FreeBASIC

    58/255

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    2324

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    'Print decimal and binary values

    Print "Testing 3rd bit position (from right)"

    Print "myByte:";myByte," Binary: ";Bin(myByte)

    Print "Mask: ";Mask," Binary: ";Bin(Mask)

    'Check to see if 3 rd bit is set

    If (myByte And Mask) = 4 Then

    Print "3rd bit is 1"

    Else

    Print "3rd bit is 0"

    End If

    Print

    'The mask will test the 2nd bit position, i.e. 2

    Mask = 2

    'Print decimal and binary values

    Print "Testing 2nd bit position (from right)"Print "myByte:";myByte," Binary: ";Bin(myByte)

    Print "Mask: ";Mask," Binary: ";Bin(Mask)

    'Check to see if 2 nd bit is set

    If (myByte And Mask) = 4 Then

    Print "2nd bit is 1"

    Else

    Print "2nd bit is 0"

    End If

    Sleep

    End

    )isting .!+ and.bas

    Analysis n line the *orking ariables are declared and initiali ed. he firstsection of the program is testing for the third bit position of my0yte, *hich is bit ' ' , ordecimal . $ines G through &5 print out the heading, decimal and binary alues for the

    ariables. he f statement in line &A uses the 1!# operator to test for a & in the A rd bitposition, and since binary contains a one in this position, the program *ill e ecute the

    code immediately follo*ing the hen key*ord.$ine '& sets the mask alue to ' to test for a & in the second bit position, *hich is

    ' & or '. $ine 'A through ' print out the header, decimal and binary alues of theariables. 8ine 'G uses the 1!# operator to test for a &, and since binary has a 5 in this

    position, the program *ill e ecute the code immediately follo*ing hr Else key*ord.

    Running the program produces the follo*ing output.

    &4

  • 8/20/2019 2. FreeBASIC

    59/255

    Testing 3rd bit position (from right)

    myByte: 5 Binary: 101

    Mask: 4 Binary: 100

    3rd bit is 1

    Testing 2nd bit position (from right)myByte: 5 Binary: 101

    Mask: 2 Binary: 10

    2nd bit is 0

    )isting ."+ ,ut-ut o and.bas

    $ooking at the binary alues you can see ho* the bits line up and ho* the 1!#operator can test for indi idual bits. in binary has a bit set in the ' 5 (&) and ' ' ( )position. etting the mask alue to sets bit position ' ' to & and all other bit positions to

    5. he e pression (myByte And Mask) *ill return an integer alue that *ill contain the1!# alues of the t*o operands. ince the mask has eros in e ery position e cept forthe ' ' position, all of the other bits *ill be masked out, that is 5, returning a . ince thereturn alue of matches the target alue , the code follo*ing the hen clause ise ecuted.

    he second portion of the program test for the ' & position of my0yte. ince thisposition contains a 5 in my0yte, the alue returned from the e pression (myByte AndMask) does not match the target alue, so the code follo*ing the Else clause if e ecuted.

    2he ,R ,-erator ;ou can use the :R operator to set multiple alues in a single ariable. he

    4indo*s 1P uses this techni7ue to set flags for ob ects such as the styles of a *indo*. he follo*ing program illustrates this concept.

    1

    2

    3

    4

    5

    6

    7

    89

    10

    11

    12

    13

    14

    15

    16

    Option Explicit

    'Declare working variable

    Dim As Byte myByte, Mask

    'Set the flags in the byte

    myByte = 2

    myByte = myByte Or 4'Print decimal and binary values

    Print "myByte set to 2 and 4"

    Print "myByte:";myByte," Binary: ";Bin(myByte)

    Print

    'Set the mask to 2

    mask = 2

    Print "Testing for 2"

    'Check for 2 value

    &5

  • 8/20/2019 2. FreeBASIC

    60/255

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    3334

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    If (myByte And Mask) = 2 Then

    Print "myByte contains 2"

    Else

    Print "myByte doesn't contains 2"

    End If

    Print

    'Set the mask value to 4

    Mask = 4

    'Print decimal and binary values

    Print "Testing for 4"

    If (myByte And Mask) = 4 Then

    Print "myByte contains 4"

    Else

    Print "myByte doesn't contain 4"

    End If

    Print

    'Set the mask value to 8Mask = 8

    'Print decimal and binary values

    Print "Testing for 8"

    If (myByte And Mask) = 8 Then

    Print "myByte contains 8"

    Else

    Print "myByte doesn't contain 8"

    End If

    Sleep

    End

    )isting .%+ or.bas

    Analysis $ine declares the *orking ariables. n line 3, my0yte is set to ' and inline G, that alue is combined *ith using the :R operator. $ines &5 and && print out thedecimal and binary alues of my0yte. n line & , the mask is set to ' and in lines &Gthrough '' the 1!# operator is used to test for ' in my0yte. ince my0yte contains a ',the program *ill e ecute the code immediately follo*ing the hen clause. $ines 'through A& use the same procedure to test for the alue of . ince my0yte contains a ,the program *ill print out the te t Wmy0yte contains a X. n lines A through &, my0yteis tested for G, *hich is does not contains so the code in line 5 *ill be e ecuted.

    4hen you run the program, you should get the follo*ing output.

    7

  • 8/20/2019 2. FreeBASIC

    61/255

    myByte set to 2 and 4

    myByte: 6 Binary: 110

    Testing for 2

    myByte contains 2

    Testing for 4

    myByte contains 4

    Testing for 8

    myByte doesn't contain 8

    ,ut-ut .!+ ,ut-ut o or.bas

    1s you can see from the output, you can pack multiple alues into a singleariable. he number of alues a ariable can contain depends on the si e of data type

    and the range of alues. "sing the :R and 1!# combination is a techni7ue that you *illfind in *ide-spread use, especially in third-party libraries, as it pro ides an efficient *ayto pass multiple data items using a single ariable.

    2he ,R ,-erator:ne of the more useful aspects of the I:R operator is to flip bits bet*een t*o

    states. I:Ring a alue *ith 5 *ill return the original alue, and I:Ring *ith a & returnsthe opposite alue. uppose that you start *ith a & bit and I:R *ith a 5 bit. ince thet*o inputs are different you *ill get a &. f the start alue is 5 and you I:R *ith a 5, thenboth alues are the same and you *ill get a 5. n both cases the output is the same asthe input. f you start *ith a & and I:R *ith a &, you *ill get a 5 since both inputs are thesame. f you start *ith a 5 and I:R *ith a &, you *ill get a & since the inputs aredifferent. 9ere the inputs ha e been flipped to the opposite alues. ;ou can use thistechni7ue *ith a mask alue, I:Ring once to get a ne* alue, and then I:Ring again*ith the same mask to get the original alue.

    :ne use of this techni7ue is to display a sprite on the screen using I:R and thenerasing the sprite by using another I:R at the same location. he first I:R combines thebits of the background *ith the sprite bits to display the image. 1nother I:R in the samelocation flips the bits back to their original state, once again sho*ing the background andeffecti ely erasing the sprite image.

    I:R can also be used to s*ap the alues of t*o ariables as demonstrated in thefollo*ing program.

    1

    2

    3

    4

    5

    6

    Option Explicit

    Dim As Integer myInt1 = 5, myInt2 = 10

    Print "myInt1 = ";myInt1;" myInt2 = ";myInt2

    Print "Swapping values..."

    *

  • 8/20/2019 2. FreeBASIC

    62/255

    7

    8

    9

    10

    11

    12

    13

    myInt1 = myInt1 Xor myInt2

    myInt2 = myInt1 Xor myInt2

    myInt1 = myInt1 Xor myInt2

    Print "myInt1 = ";myInt1;" myInt2 = ";myInt2

    Sleep

    End

    )isting .&+ 8or.bas

    Analysis n line A the *orking ariables are declared and initiali ed. $ine printsout the initial ariable alues. $ines 3 through H carry out the I:R operation. n line 3,

  • 8/20/2019 2. FreeBASIC

    63/255

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    2829

    30

    31

    32

    33

    34

    35

    26

    37

    38

    39

    Print "Statement (myInt1 < 5) eqv (myInt2 > 1) ";

    If (myInt1 < 5) Eqv (myInt2 > 1) = True Then

    Print "is equivalent."

    Else

    Print "is not equivalent."

    End If

    Print

    'Both statements are false so are equivalent.

    Print "Statement (myInt1 > 5) eqv (myInt2 < 1) ";

    If (myInt1 > 5) Eqv (myInt2 < 1) = True Then

    Print "is equivalent."

    Else

    Print "is not equivalent."

    End If

    Print

    'One is true, the other false so statement

    'is not equivalent.

    Print "Statement (myInt1 > 5) eqv (myInt2 < 1) ";

    If (myInt1 > 3) Eqv (myInt2 < 1) = True Then

    Print "is equivalent."

    Else

    Print "is not equivalent."

    End If

    Sleep

    End

    )isting . + e '.bas

    Analysis n lines A and , the alues False and rue are defined. Free0asic uses -&to indicate a rue result from a logical operation such as that performed *hen e ecutingan f statement. ince False is defined as 5, !: False flips all the bits to &, including thesign bit, making -&.

    n line 6 the *orking ariables are declared and initiali ed. $ines &' through &G testthe first e pression. he f statement in line &A *ill e ecute the first e pression, (my nt&

    ). ince this *ill return rue. he E>% operator has lo*er precedence then

    (my nt' &), so this *ill be e aluated, and since ' & then *ill also return true. hislea es -& E>% -& to be e aluated. ince -& is e7ui alent to -&, the *hole statement is rue. n line '', both of the e pressions are False. 5 E>% 5 is rue, so this statement isalso rue and *ill print out the affirmati e. n line A', the first e pression is rue *hile thesecond is False. ince -& is not e7ui alent to 5, this statement *ill e aluate to False andthe negati e *ill be printed.

    4hen the program is run, you *ill see the follo*ing output.

    "

  • 8/20/2019 2. FreeBASIC

    64/255

    myInt1 = 4 myInt2 = 2

    Statement (myInt1 < 5) eqv (myInt2 > 1) is equivalent.

    Statement (myInt1 > 5) eqv (myInt2 < 1) is equivalent.

    Statement (myInt1 > 5) eqv (myInt2 < 1) is not equivalent.

    )isting .6+ ,ut-ut o e '.bas

    t is important to reali e that you are not testing to see if the e pressions are rueor False. ;ou are only testing to see if the e pressions are e7ui alent to each other. o putit another *ay, you are testing to see if t*o assertions are e7ui alent to each other. Fore ample, suppose you ha e t*o characters in a game and you *ant to attack *ith bothcharacters, if they are at e7ui alent strength. ;ou could build an e pression similar to theone in the listing and take action based on the e7ui alence of the t*o characters.

    2he MP ,-erator$ike the E>% operator,

  • 8/20/2019 2. FreeBASIC

    65/255

    ,-erator 03nta8 Co$$ent

    mpQ 0 mpQ C his is the same as 0 Q 0mp C.

    2able .!+ 0hortcut Bit#ise ,-erators

    2he 0H) and 0HR ,-erators9$ stands for shift left and 9R stands for shift right. 1s the names imply, these

    operators shift the bits of a byte or integer-type ariable either left or right. he follo*ingtable sho*s the synta diagram of both operators.

    ,-erator 03nta8 Co$$ents

    9$ ( hift bits left) 0 Q ariable 9$number

    hifts the bits of ariable left number ofplaces.

    9R ( hift bits right) 0 Q ariable 9Rnumber

    hifts the bits of ariable right number ofplaces.

    2able ."+ 0H) and 0HR ,-erators

    hifting left is the same as multiplying by ' and shifting right is the same asdi iding by '. ;ou can see this by looking at the binary representation of a number. akethe byte alue of & *hich is 5555 555&. he & is in the ' 5 position. ' 5 e7uals &. hiftingthe bit left, makes 5555 55&5, putting the & bit in the ' & position, *hich e aluates to '.

    his is the same as &N'. hifting left again puts the bit at the ' ' position, 5555 5&55*hich e aluates to , or ' N'. hifting the bit right puts the & back in the ' & position,

    5555 55&5, *hich e aluates to ', or /'. hifting right again puts the & bit in the '5

    position, 5555 555&, *hich is & or '/'. he shift operation can be used as a replacement for multiplication or di ision if

    you are *orking *ith po*ers of ', but it is primarily used to pack data items intoariables, or to retrie e data items from ariables. ;ou sa* this demonstrated in the

  • 8/20/2019 2. FreeBASIC

    66/255

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    Print "myInt = ";myInt

    For i = 1 To 8

    myInt = myInt Shl 1

    Print "myInt = ";myInt

    Next

    Print

    'Divide by powers of 2

    Print "Shifting right..."

    Print "myInt = ";myInt

    For i = 1 To 8

    myInt = myInt Shr 1

    Print "myInt = ";myInt

    Next

    Sleep

    End

    )isting .4+ shlr.bas

    Analysis $ine declares the *orking ariables, my nt *hich *ill be he alue that isshifted, and i for use in the For-!e t loop. $ine G through && shift my nt left &6 times, & bitposition each time, and prints the result. $ine & through &H then shift the ariable right&6 times and prints the result. he program is closed in the usual *ay.

    Running the program produces the follo*ing output.

    Shifting left...

    myInt = 1

    myInt = 2

    myInt = 4

    myInt = 8

    myInt = 16

    myInt = 32

    myInt = 64

    myInt = 128

    myInt = 256

    Shifting right...

    myInt = 256

    myInt = 128

    myInt = 64

    myInt = 32

  • 8/20/2019 2. FreeBASIC

    67/255

    myInt = 16

    myInt = 8

    myInt = 4

    myInt = 2

    myInt = 1

    ,ut-ut .%+ ,ut-ut o shlr.bas

    1s you can see from the output, shifting left multiplies the alue by ' and shiftingright di ides the alue by '.

    Bit#ise MacrosFree0asic has se eral built-in macros for retrie ing and setting bit and byte data

    from a ariable. he follo*ing tables lists the macros, the synta and their definitions.

    Macro 03nta8 De inition

    9i*ord 0 Q 9i*ord( ariable) Kdefine 9i*ord( ) (C" nt( ) shr &6)

    $o*ord 0 Q $o*ord( ariable) Kdefine $o*ord( ) (C" nt( ) and 6 A )

    9ibyte 0 Q 9ibyte( ariable) Kdefine 9ibyte( ) ((C"int( ) and 6 'G5)shr G)

    $obyte 0 Q $obyte( ariable) Kdefine $obyte( ) ( C"int( ) and ' )

    0it 0 Q 0it( ariable, bitTnumber)

    Kdefine 0it( , bitTnumber ) ((( ) and (&shl (bitTnumber))) 5)

    0itset 0 Q 0itset( ariable,bitTnumber)

    Kdefine 0itset( , bitTnumber ) (( ) or (&shl (bitTnumber)))

    0itreset 0 Q 0itreset( ariable,bitTnumber)

    Kdefine 0itreset( , bitTnumber ) (( ) andnot (& shl (bitTnumber)))

    2able .%+ Bit#ise Macros

    he 9i*ord macro returns the leftmost t*o bytes of an integer and the $o*ordmacro returns the the rightmost t*o bytes. he 9ibyte macro returns the leftmost eightbits of a an integer and the $obyte returns the rightmost eight bits.

    he 0it macro returns a -& if a bit at position bitTnumber is a &, other*ise it returns

    a 5. he 0itset macro sets the bit at position bitTnumber to & and returns the number,and the 0itreset macro sets the bit at position bitTnumber to 5 and returns the number. he rightmost bit is bit 5 follo*ing the binary numbering scheme.

    Caution 0it*ise operators *ill only *ork correctly on byte and integer-type data. 1single or double-type ariable that is passed to a bit*ise operator *ill be implicitlycon erted to an integer, *hich may result in precision loss.

    6

  • 8/20/2019 2. FreeBASIC

    68/255

    hese macros are useful *hen *orking *ith third party libraries such as the4indo*s 1P , *here se eral pieces of information are stored in a single data type.

    A )ook Aheadn addition to the arithmetic and bit*ise operators, Free0asic has a set of

    mathematical functions *hich is the sub ect of the ne t chapter.

    4

  • 8/20/2019 2. FreeBASIC

    69/255

    6 Mathe$atical FunctionsFree0asic has a number of mathematical functions *hich are listed in the follo*ing

    table.

    Function 03nta8 Co$$ents

    10 (1bsolute %alue) 0 Q 1bs(e pression) Returns the unsigned alue of e pression. his is an o erloaded function soe pression can resol e to an integer,longint or double.

    1C: (1rcCosine) 0 Q1cos(e pression)

    Returns the 1rcCosine of a double-typee pression in radians. E pression must bein the range of -& to &.

    1 ! (1rc ine) 0 Q 1sin(e pression) Returns the 1rc ine of a double-typee pression in radians. E pression must bein the rang