Home
MISOSYS LC - tim
Contents
1. FROM THE AUTHOR The product which you have in your hands affectionately called Elsie has been a labor of love She has grown with my children who have shared in this labor by giving up time with their father My wife Sam has nourished Elsie with her understanding kindness and love and has sacrificed her time as well I have long awaited the day when Elsie would be completed so that I could share more with them This family whom I love dearly is my greatest earthly treasure beyond price My Heavenly Father s love and patience and the gifts he has blessed me with are what made it all possible I pray that you will share in my blessings in some way through whatever Elsie brings your way Elsie has grown from a small seed of generosity Ron Cain s Small C compiler Ron published his compiler and placed it in the public domain for all to hack and many have done so Ron Cain deserves our heartfelt thanks for stirring up interest in the C language and for getting us started Elsie was bootstrapped using Small C and she shows her roots in places It is my hope that Elsie will bring the C language to a less experienced audience than that which the language now appeals to I am sure there are many who with just a little help getting started with C will become excellent C ers Elsie would not be here if it had not been for Roy Soltoff of MISOSYS He has been a generous benefactor and friend giving of his time hardware
2. 7 7 7 7 7 7 7 NAME NAM LC identifier 1 to 8 characters E Upper case l The temporary label number BEEN ae m The function number within the module l l oe O P ee PU S ume ORB Ge wc A FU FU eee ee Ge E HUND PD W PU W guis a wie m SD n 4 UP Geb Gn Uo Gu Sl um AUD O O Cum Ore m CUD GEM GU Gee fe pP HUP am EP AGED am UND am Cum e um LC generates labels in this fashion so that static variables external variables and labels will not conflict with each other Thus there can be an external variable named x a module static named x in two different modules a static named x in two different functions in the same module and a goto label named x all within the same program with no conflicts The TT module substitution character in the labels will make labels unique Within each module while the function number appended to labels will make labels unique within each function A dollar sign is appended to external labels which are three characters long or less This prevents possible conflicts with register names and logical operators in EDAS Temporary labels are used by LC to implement conditional statements and operators and loops They are assigned numbers starting at 1 and incrementing by 1 The dollar sign as the first character allows you to suppress all temporary labels from your symbol table output by using the SL Sw
3. option tnlib 2 main int xl evar til for xl P yl P x2 127 t g t lt 47 tt 5 linell x1 yl x2 t line Q x1 yl x2 t for y2 47 t 127 t B t 2 t line 1 xl yl t y2 line 8 xl yl t je dl exit 0 INSTALLATION LIBRARY 7 x H E cm T Le LIBRARIES PLOTTING CONTROL FUNCTIONS REEE Z T Two functions are provided that interface with and control certain aspects of the pixel plotting functions The pmode function establishes the CRT image area as one of the four quadrants in the cartesian coordinate system Another function ploc establishes the starting address of the CRT image area The syntax of these functions is qo su quim quim m mue Me AUD AA do OF que OU m que que ui im en mue A ue qm ee d aue dE ee aum WAR uum e WAR UEM Gub UE uum m VEND a uum MUS Cum apum By pu due QN cpu um ee AD com vea ploc address retcod pmode quadrant address specifies the starting address of the plotting image area Plotting functions use 2m the CRT address unless changed by pmode quadrant sets the plotting image to quadrant 1 45 of the x y plane initialized to quadrant 4 If quadrant then the current quadrant number in effect will be returned or quis SEND UA GER iak iat duum ee E mr d ee far O RAD GU GAS Uk apr qar anr ge O O ee eee VAR apr y ey ee ee
4. char names char words o e s e e o e e e Both of these declarations result in the same effect a pointer which points to a Pointer which points to a character field Pointer variables may have up to 32 levels of indirection However the practical limit is the ability of the programmer to keep track of all this In general two levels of indirection are all most folks can take More information and examples can be found in the reference text The C Programming Language by Kernighan amp Ritchie DECLARATIONS 2 8 E LANGUAGE DEFINITION SCOPE OF VARIABLES amp FUNCTIONS ESNIIEDIZZ ALIADA E Variables or functions which are declared outside of any function i e are not parameters to functions or declared with braces are called external They are external to all functions External variables and functions can be used from any of the functions within the module being compiled Using the extern statement an external variable or function may even be accessed from another separately compiled module Please do not confuse extern and external External to all functions variables and functions can be declared without the extern statement The extern statement is explained in full detail below Variables declared within a function are called local Functions may not be defined within another function as is the case with the Pascal language However a function may be DECLARED ex
5. control is a string as specified under PRINTF argn are arguments as specified under PRINTF RETURN CODE The retcod will be zero if no error was detected in the output operation If an error was detected then retcod will be EOF 1 STANDARD LIBRARY 4 8 LC LIBRARIES FPUTS Sd I retcod Kia string fp Serang is the address of the string to be output FputsQ outputs to the file defined by fp all characters pointed to by string up to the first zero byte RETURN CODE The retcod will be zero if no error was detected in the output operation If an error was detected then retcod will be equal to EOF l 1 bon uod Calling fputs with an invalid file pointer can result in destruction of files or other havoc STANDARD LIBRARY LC LIBRARIES FREE This function frees memory allocated with alloc Its syntax is free ptr ptr address of the bottom of the memory block Free is called when a memory block allocated to the program by the function alloc is no longer needed and the programmer wishes to free the memory space for later use ptr points to the first lowest byte allocated to the program by alloc RETURN CODE There is no return code WARNINGS a AR Calling free with an address other than that obtained from a call to alloc will cause unpredictable results mem progra
6. STANDARD LIBRARY 4 19 LC LIBRARIES ptr sbrk nbytes nbytes an unsigned integer number of bytes needed TP ah aie UO Ah GuP CUM By VU Wy m me Axe d TUO UP NP MUROS dU aum UD UND C M SUED CUPS Vh dde Ma eq Gee umm ba Bek xime dE que Ab vun GP UH FUP OP An aw GP CUP mime Eh UP ohh A dup Gu A vum mme A BA umm Rr EP nm Z Ge a ame nb RA UAM Sus UD mm MAP quee UD que um AP O QUID QUD Ama Fe O UD Ty mm Que UU qua He Th Cs VER eee is KAP iae AP ume nie Ge UD CUM TK Anh vp COP uM e Ab CUL Nb um mum TER ee O Ge E cu uA UO Am M Sbrk reserves memory for use by a program from the system memory pool The memory allocated by sbrk cannot be deallocated until the program finishes execution Alloc uses sbrk to request blocks of memory as needed If the memory requested will only be needed for part of the execution of the program it is recommended that alloc be used _ RETURN CODE The return code ptr is the address of the allocated block of memory if the sbrk was successful If not enough memory is available to satisfy the request ptr is set to NULL WARNINGS am u We dU om QUA VUL UA Only memory allocated by sbrk or alloc should be used by the programmer for dynamic space File opens and closes including standard files use these functions for setting up File Control Areas FCA s These FCAs can be clobbered if the program accesses unauthorized memory
7. The function cmdi will invoke an exit from the running LC program and schedule the DOS execution of the command contained in string command string This could be used for instance to chain to another C program The cmdi argument can be either a string defined in the function call or a pointer to a character array which contains the command string If you want to execute a command and return to your LC program use the cmd function This function will pass the command stored in string command string or the string pointed to by a pointer argument to the DOS command interpreter Upon completion of the command control will be returned to the running LC program Your program and variables will be saved during the INSTALLATION LIBRARY 4 35 LC LIBRARIES execution of the command If the executing command returns through EXIT a return code of zero 9 will be retrieved If the ABORT exit is taken the return code generated will be obtained from the value contained in register pair HL If this value is positive i e bit 15 reset it becomes the return code If the value is alu i e bit 15 set then a negative one 1 will be returned TAE CALL m oam ay da Gm Um A generalized assembly language interface routine call is available in the installation library Regs is an integer array of dimension 6 which Should contain the quantities you want placed into the register pairs AF BC DE HL IX and IY for
8. compatibility with other C language systems the programmer should not depend on exit to Close the program s files other than standard 1 0 files STANDARD LIBRARY 4 4 P LC LIBRARIES DATA CONVERSIONS ATOI ITOA XTOI ITOX HEEE LEDS LEE E E G E AS These functions are used to convert character strings of digits decimal or hexadecimal to their integer value and vice versa The syntax is as follows H tf H it H it i if i H ti 11 u H H H H 14 H it if H ti ie it il if H it 5 it it H i 11 il H it H it li i H H H int atoi decs itoa int decs Ant xtoi hexs itox int hexs f x int os is an integer value decs is a string containing decimal digits 8 9 hexs is a string containing De aue nal digits 0 5 4 9 lt A F or lt a f gt These standard C functions are used to convert integer values to their character string image and the converse Functions are provided to deal with character strings containing either decimal or hexadecimal digits Left truncation of the integer value takes place if an excess number of digits is present i e int xtoi 11999 would result in the integer value of 4896 o decimal Conversion of a decimal string will be modulo 65536 Notes the C itoi function has not been implemented for obvious reasons Bs E RETURN CODE inns
9. filespec A file specification for the input file s A maximum of 8 filespecs may be passed switch Represents an optional compiler switch es These switches are preceded with either a plus sign on or a minus sign off we 9 gu ap UMD unm unam SES SU a ae UAM GP a A GA uum dd A A uum Cr qum AA qua AAA AU AA ae UV DS uum um DO an om ON UND cup UND W dM uu UND TW quas dM Gb UM upm UAM quip ean Ga CAM UD ae upp AAA CUP qup ow GEB su CUP GAS cue UA uu aw awe ow aw ew et ow wwe UM OE ow GENS VEND asm ee ee UAR YP AMA cup AD UMR CAM quM GUB CAM anm anm DN SEED Gum A PU Gumm iun ems TP dann oe FU APA sam A PP aum cep cep eee eee UNES GRADO AMD dans The compiler is executed by entering a command line such as LC CPROGRAM 2 LIST which compiles the LC source file CPROGRAM CCC and generates the output file CPROGRAM ASM on drive 2 The LIST switch specifies that you want the LC source code listed to the screen during the compilation process The switches allow the user to control certain features of the compiler Switches and filenames may be intermixed in any order on the command line The simplest compilation command would simply be LC PROGNAME which compiles the file PROGNAME CCC and generates the output file PROGNAME ASM FILE SPECIFICATIONS There may be up to eight input file specifications given on the command line They are processed by the compiler in the order they occur left to right If no exte
10. A Z Xn else printf Character is none of the above n STANDARD LIBRARY 4 15 LC LIBRARIES PRINTF This function creates a formatted image for standard output Its syntax Et ASE 2n p it ii H n it u il il ii i if i H if li u H ii u 1 it H u u H ii H it i ii u tl ii ii n ii H it MH u i i u i ii il i H H ji ii ii H H H H i it i H H i printf control wd arg2 control isa string containing transparent printing Characters and conversion specifications argn are arguments to be formatted for the output print image d ce i eee ee te pu 9 A sm dum pt quus GER AU om GAS VU uP ee w Ga cp uns due Oe C VO aby Gu SM dum uum due oe dum UVP THP abn EC A UU TA rd Gum HER ee Cale CEP a epe d MA ae oer ow om uM ow a A ow Gui UNT a UE oe SU ow oF WR MU au AMA AM cA Que Quem AP CE E uum Bg Quas AA GNE CU Por ee am P OR GUB Que au KM One um 4e CU ua fer Quae ACE CUR dua CUR CR CP AP Tp P GUB nip GAP CUM su See EM CD Om am om Gub Cre cab ie om wen Cabe Que wm This function is used to create an output image to the standard output device The specifications for formatting the output are determined by the character string control This string will contain ordinary characters copied directly to the output image and or specifications denoting the field conversions of all arguments The conversion specifi
11. C js the character to be output E US om dub C tb un din OS VE quA CHD Gua UR RUP We Dem Gum dip qum oe Ge UD oD dee a as qe dy cum ue dee Dem Kg Pot eee de di qua uis uu edm quus RPM de SRM UND cu A din Mot WR Quas Mot UE T que Map quium Mat Mat e CUP dee dinb Ue um GU GU qup up d es UNE Rum dux Gage EUR WEN URS Get UU rr a CUM ipe 9 HAMA uu SUE Quis FU quu Rum SPUR DUM UM N T GP GA Duce FUA AS UD SER CUR Ram TUUM GM Gee GER PE Ue Ger eve Gays E Geh ue P Gum cm ae Putchar outputs the character c to the standard output file Putc is used to perform the output operation RETURN CODE The return code cret is the character passed in c df no errors are detected WARNINGS There are no warnings STANDARD LIBRARY 4 18 LC LIBRARIES PUSO ZI This function is used to output a string to the standard output Its syntax is retcod puts string string is the address of the string to be output Puts outputs lt string gt to the standard output file All characters up to the first zero byte are output If an error occurs during output the value EOF 1 is returned otherwise a zero is returned RETURN CODE The retcod will be zero if no error was detected in the I O operation If an error was detected then retcod will be set to EOF 1 WARNINGS There are no warnings EXAMPLE Vf argc 3 A puts Format error compare filel file2 n exit s
12. GUA ee ee ee ee eee SUD UA eee ee ee ee ee e um SEE iak gik REA a a AA Gus Z fd fde NEED UU Gin et Gak Ce Cue fG ff Piu ff NEED REED NEED ee ee CDUP eee UU GEN UH RUD i apu CUN NND GU GAP ee Ane W ame Ae e ER e A RR W p The pmode function is quite useful when your application concerns the graphing of mathematical functions in the standard cartesian coordinate system Since most functions are graphed in the first quadrant a pmode 1 will establish the image area for that purpose Please note that any characters graphics currently on the screen at the time the pmode is given are left undisturbed pmode does NOT refresh the current screen contents to the revised quadrant but prepares the plotting functions for the new quadrant Quadrant is used when changing the base origin of the plot image area with the pmode function The image area is considered to represent only one quadrant of the x y plane in the cartesian coordinate system The quadrants are numbered as follows with the point 9 9 the origin appearing at the corner identified with the letter O The standard quadrant used by the plotting functions will be quadrant 4 unless changed with a pmode function call Remember that the direction away from the origin is always considered to be positive The ploc function can be very powerful in creating dynamic displays By establishing an off CRT buffer equal in length to the CRT image area its INSTALLATIO
13. INSTALLATION LIBRARY iliis LC LIBRARIES a8bcde abc abcd Jim karl rich roy this is a long string Keep this ordered list in mind in the following examples The statement if strem abe aBbcd lt 9 printf above printf below should print the word below since the string abc is below the string aBbcd in an ascendingly sorted list The statement df strcmp abc abcd lt p printf L above printf below should print the word above since the e abc is above the string abcd in an ascendingly sorted list STRCPYO The strcpy function copies an image of the source string to the destination string buffer STREPL The function strepl replaces that portion of the destination string starting at relative position pos and continuing for count characters the destination substring with the source string The arguments pos and count control where and how much of the destination string is to be replaced i e what is the substring The length of the replacement string is the length of the source string If count is zero then an insert operation is performed without deleting any characters of the destination string If the source string is null i e of zero length then only the identified sub string is deleted If dest pos exceeds the bounds of the destination string an out of range error will be returned and the s
14. missing semicolon No semicolon was found at the end of a Statement The character is the statement terminator and must be placed at the end ofa simple statement 85 gt must be constant The size of an array must be a numeric constant 86 must be extern function declaration was encountered past a comma in an external but not extern declaration statement This context implies that the function is of storage clases extern but this was not the class of the declaration statement 87 must be lvalue The etin being processed specifies that a value be placed into an object but no object which could be stored into was found 88 gt negative size illegal An array witha negative size was declared The array size is made positive before being used 89 nested too deep ignored The include statement wou 1d have nested too deeply if not ignored Up to eight 8 nesting levels are available in LO ves M LE E 9 no closing brace The end of the last input file was encountered without closing brace for the current function being found 91 gt no input file No input files were specified on the command line which invoked LC o E 92 no multiple dimensions The array being declared has more than one dimension which is not Supported LC supports one dimensional arrays only 93 gt no while after do A do statement was compiled but no while Statem
15. string while c getchar EOF if comment if c e01 tab comment string else continue else if c if string comment 1 continue else if c e01 tab string else if c string string if whitespace c tab 1 continue else if tab putchar t tab colt if c eol if col continue col 1 putchar c col exit 9 whitespace c int c if c NT Coss t return 1 else return DECOM CCC D 5 APPENDIX SAMPLE PROGRAMS Plot Hilbert curves of orders 1 to n include stdio csh foption INLI8 dnt h x y x0 W u v main int i n hf puts x f xlc x1fhi Ibert gurvan n 4 h 32 129 h hp xG h 2 x while i lt n h 2 MW h 2 W Wrh 2 xj i 32 ee u X v y ed p 1 1 exit move int i j for i min x u i lt max x u 1 1 for jemin y v s j lt max y v 1 j lt pixel l i du UTX VEY returnig min a b int a b if a gt i return b else return a max a b int a b if a lt b B else return a p typ 7 gt int typ i df i lt return 9 else Switch typ case 1 p 4 i 1 x x h move p l i 1 y y h move p 1 i 1 x xth move p 2 i 1 yen T case 2 p 3 1 1 y y h move TN p 2 1 1 x x h
16. 4 44 attra ADVANCED TOPICS UTILIZING ASSEMBLY TIME OPTIONS A n A IIA LC provides certain options which can help the programmer to generate efficient programs These options can be specified from the C source code by using the f option statement The defaults to these options are set in the file LCMACS ASM so that no options need be s t except when the default is not the desired option Since the dfoption statement generates a DEFL statement in the assembly language source output it can also be used to control options in any user libraries or separately compiled modules If used to control options in separately compiled modules the foption statement must be n a module which precedes the module whose option is to be specified Bear in mind that an option once set can be changed by another foption Statement Thus when assembling separately compiled modules care should be taken that a later module will not change the option set in the current module unless this is desired Options which are switches can be set to ON 1 or OFF 8 These specify whether or not some option is to be active The constants ON and OFF are defined in STDIO CSH Options which are not switches may be set to the value desired by specifying the value in the option statement ARGS lt This option controls the generation of argc and argv the command line argument parsing If the option is turned ON the arguments
17. also called a block can be used anywhere that a simple statement may be used Thus wherever LC s syntax requires a statement more than one statement may be given by enclosing them in braces Within the compound statement there may be any combination of simple and compound statements The compound statement has the format declarations statements No declarations or statements are required although the use for an empty block would be as a null statement of sorts The declarations should appear before any statements Any of the statements may in turn be another compound statement No semicolon is required after the compound statement 1 The only place where a compound statement is required instead of a simple statement is in the body of the switch case statement The body of a function is one compound statement Here are some examples of compound statements func o the body compound statement a b simple statement if ac m X another compound statement c a b a STATEMENTS eed Pl ee a R eee ee LANGUAGE DEFINITION X end of gnr statement return atbtc end of function body compound statement NULL STATEMENT A null statement is a sort of place holder LC requires that a statement be given in certain places If no action is needed in the place required then the null statement can be used No action is taken by the null stat
18. if you are using a Model I use the CDO FLT filter in your configuration to filter the video driver The filter presents more usable character indications for the characters Nn J and 7 This working system diskette can be created by using the LDOS PURGE utility on a fresh backup of LDOS You may remove all files except SYS SYS4 SYS6 SYS8 SYS1 SYS12 Keep any other file you use frequently for instance BACK UP and FORMAT If you are using a double density system follow steps GV If you are using a single density system follow steps GB 3A A 4g track double density minimal system diskette per the above has about 144K free Copy EDAS CMD from the working EDAS diskette Then copy all of the files from the working LC backup to this LC system diskette This should still leave some work space Use a data diskette in your second drive for LC source files and all files output by LC and EDAS 3B A 35 c single density minimal system diskette per the above has about 57K free Copy EDAS CMD from the working EDAS diskette then copy LC CMD LC JCL LC ASM LCMACS ASM and STDIO CSH from the working LC backup to the new System diskette We ll call this diskette your LC System diskette Now remove the LC CMD LC JCL LC ASM LCMACS ASM and STDIO CSH files from the working LC backup the one you just copied FROM not the system disk that just received those files Re designate this disk your working LC Data disk In a
19. is zero the destination becomes a null string If the count is greater than the source string length the entire source string is copied STRLEFT The function strleft will replace the destination string with the leftmost count characters of the source String If count is zero the destination becomes a null string If the count is greater than the source string length the entire source string is copied STRLEN The gt strlen0 function returns the length of the Source asa smo The Function ido will replace the destination string with the s bs rng of count characters starting at position sourcetpos of the source string If count is zero the destination string will be null Also if source pos exceeds the bounds of the source string an out of range error 1 will be returned and no string replacement will occur Count may be greater than the length of source plus pos INSTALLATION LIBRARY T LC LIBRARIES STRING FUNCTION ARGUMENTS The string functions specified above reference various arguments detailed as follows DEST This represents pointer to a character array The argument that is passed to a function is an address when the argument references an array therefore a pointer is identified to the string functions by the very nature of the character array declaration as in char s 81 which establishes a character array capable of holding up to an 8
20. CAMARA lt A RARA eR KARR RI II IK RARA RAR RARA RARA R A AAA IAN 5 lt lt erre MISOSYS LC C Language Compiler kkkkk gt gt Cice Copyright 1982 by Jim Frimmel 0 Yee CCUARAAKAKERKRARERK ke de d ke k de AKA ke ke de de de KAA AAA KAK K RARA AAA AROS CII KI I RIK III RIKI dee de de de e ke de de de ke de de de dede de e e KA e e KAA dk e de e de ke dee eke kS Table of Contents Forward TP 989000090080 er ere From the Author ae ee a 2 66 66 o Preface v 99 99 999 9999 90 9 9 9 59 98 00 9 9 006 909099 099 99990925999259929 4 209 Introduction iuis 9909 60400900051009000009900000 0090500009009 Elsie Files 00950900009000 600090900000020909098000000 LC Environment LRAOorn n n e o ne nop E Standard Input Output ooooooooomooomoooososoo Standard 1 0 Redirection sesiones Standard Header Files ssc s c sia Function Libraries 2A WU 9 9999999 9 4909 9 See SS eS eee Closing Comments COCO RHO RH BRO eR REDS 6 oe EEO EEE ODS Language Definition TERA ENANA 6 e6 d 6666 R 66 6 Program Environment Functions s950906009960000020 069 Statements Simple Compound eee m i LC Creating a CMD File Dieese ieas E A Data Representation Constants eessoosssoss Variable Names Identifiers c eere Data Declarations c o nee 66 e 66 KR 6 AA 606 encon 606 A A66 Scope of Variables amp Functions ooomooomoooooo
21. GETW NAME The GETW macro fetches the pBh integer stored at FNAME into the HL register HS NUM The KHS macro points HL to the value SP NUM SP refers to the stack pointer It is used to obtain the address of a local variable PUTB fNAME The PUTB macro writes the character in the L register into character variable at FNAME Seun NAME The PUTW macro will write the integer value in HL into the two byte integer variable at FNAME ASM OUTPUT STRUCTURE 5 19 1N j t oa e e Pun ADVANCED TOPICS LC IDENTIFIER OUTPUT XC makes extensive use of the MOD directive in EDAS This EDAS assembler directive causes a unique one or two character alphabetic string to be assigned to a GET SEARCH module This replacement string is incremented each time another MOD directive is encountered Every occurance of in a label is then replaced with the module s unique replacement string For more information on the MOD directive see chapter five in your EDAS manual The following table outlines the format of label generation from LC F 1 IDENTIFIER CLASS LC OUTPUT Mau A SEAE a Temporary labels 74 MEM l m External identifiers NAME longer than 3 characters NAME E 3 characters or less _ NAM Static identifiers Es external to functions NAME internal to functions _ NAME QT m Goto labels NAMES
22. GM aue e GER Hus APP e aar agus CUP UND auus uum Guns UNDA UNA cw Qus Ge UR Fopen allows the programmer to initiate access to a file Except for standard input output and error files which are automatically opened all files must be opened using fopen fspec points toa file specification string mode points to a string defining the mode of access Allowable modes are read write or append Only the first character of mode is checked and that character may be upper or lower case The file pointer is used whenever access to the opened file is needed If zero is returned an error occurred during the open process RETURN CODE The file pointer fp is returned if no errors are detected in the open operation fp will be set to NULL zero if an error is detected during the open operation WARNINGS Opening the same file for both input and output with two or more calls to fopen should NOT be done If the file is accessed in this manner it Will create unpredictable results possibl causing loss of file integrity getfile fname char fname FILE fp if fp fopen fname r NULL EMT error 2 s n fname exit else return fp STANDARD ee LC LIBRARIES FPRINTF Nr This function is used to create a formatted image for output to a device file Its syntax is MLB MEE MN AME retcod fprintf fp control argl arg2 fp E isa file pointer
23. L 3 3 L 3 4 3 t 3 3 l E S oe i cu ee QUA c fa Binary operators act upon two expressions together The type of the result depends on the type of the two expressions If the type of any of the expressions is char short or long it is treated as an integer If one expression is unsigned the other expression is treated as unsigned as well and the result is unsigned If one expression only is a pointer the result of the expression is a pointer of the same type If both expressions are pointers the result is unsigned When several binary expressions are concatenated together without isolating parentheses the order in which the binary expressions are evaluated depends on the precedence of the SEE 2 in the expression In the expression atb c the evaluation of b c precedes the evaluation of the addition since multiplication has a higher precedence than addition The expression is evaluated like this at b c AS previously described isolating parentheses can be used to change the order of evaluation To have the addition performed first the expression can be written B a b c Each class of operands is described below in order from the highest precedence to the lowest Note that when all the operators in a complex expression have the same level of precedence they are evaluated in a certain order right to left or left to right It can be said that a class of operators group left
24. O A SUED GER UM ee Rp WAP aq SR AR mP au x The extern storage class allows an external variable declared in one module to be accessed from ancther module A module is what is processed by one execution of LC i e one set of C source input Let s say that the following declaration int choice exists in modu le 1 If module 2 functions need to access this same variable the declaration extern int choice STORAGE CLASS 2 19 e ce tn ne oo nm Oe Nae deme eaea LANGUAGE DEFINITION would allow the access needed LC will not reserve any storage for choice in module 2 since the storage class extern tells LC that storage has been reserved in another module The programmer MUST ensure that the declarations are compatible between modules In other words all extern declarations must match the external declaration declaration without extern by having the same type size and amount of indirection Otherwise LC may access the variable in incorrect ways The extern statement may also be used to declare what a function returns before it is defined in the program This forward declaration allows a function which returns something other than a signed integer to be defined after it is used If the forward declaration is not given and a function is as yet undefined the compiler assumes that the function returns a Signed integer Static objects are stored in declared fixed memory space Their
25. WR Gun HU A ee uum EA UV hb ur Gum uum UR HU ww REP Que eh O UO dius hb VEM WA Gum WR iat dat Qu s en pe gum c n tes cu uw Que Cu aig Rue uium gium c n WAR cuim G rein CUM uium cuim dium ee W O gium B Ge Cd dup O auum e ee deem GD ewe t hse ee WE qu diu WE que UPC WE eee Gump WU eme UR m retcod cmd command string command DOS amp return retcod call address regs generalized call fill iad aad char zap a memory block retcod freemem fetch memory size retcod inkey Scan the keyboard retcod inport port input from a port outport port value 5 output to a port retcod curpos fetch cursor position xvm row col E the aane date s l E fetch the system late time s 5 50 os fetch the system time E cmdi command string exit amp command DOS Pp d UD B uh ee TCR um adn qe HO ww gt e s RA m Mb ee EB Ae oe COR au ee ML By es ee ee ee eee ee ee Cb JUNE UND B oun am q a CH AP cbe 2 A END OUS auus apum 009 209 culum PO ouium cedem uium B culum uium CM cuum wb culum s dise uw cue AP UNDA Kip cbr camp UR reium ee o mium nir ee Ont UA uium A O o cuum AA sU dm WU uum cum ee num m 4 4m dup um on The function fill will propagate the character char into the memory buffer for count bytes If char is passed as an integer value the low order byte is us
26. arguments leaving the original copy of the arguments unchanged Each argument is defined at the start of the function Functions also return values to the functions that call them In LC this value is always a 16 it number The value returned can be compared to placed in a variable etc Functions can appear in an arithmetic expression anywhere that a constant can Here is an example of a function square num int num return num num The function square returns the square of a number in other words the argument num is multiplied by itself and the result is returned Arguments are listed in parentheses after the name of the function separated by commas These arguments must be passed by the calling function in the same order as they appear in this list The BODY of the function is the group of executable statements that are within the braces and Actually the grouping of statements in between braces denotes a special kind of statement called the COMPOUND statement The compound statement is fully explained in the section on LC language statements Every LC program has a special function called main which is always the entry point to the program When referencing a function within this narrative we will put after the name to identify it as a function This is close to the way it looks in an LC program The function main calls other functions which in turn call other functions etc Thus each prog
27. characters following the macname the definition The compiler will substitute the string wherever macname is found in the LC source stream It is strongly recommended that macro macnames be defined in upper case characters so that it becomes distinct when looking at your source code macname must be a valid LC identifier whereas the lt definition gt is anything and everything up to a comment or the end of the line The definition is substituted whenever the lt macname gt is encountered in the LC Source code input past the define of lt macname gt An examp le of the use of define follows finclude stdio csh define PRINTX printf Xd n x main int x x 3 4 5 6 PRINTX x 3 4 5 6 PRINTX LC OPERATION 3 4 OPERATOR GUIDE for tion mm oum ar Aa e m D foption lt optname gt value The option directive is used to pass symbol definitions from the LC source code to the assembly phase The lt optname gt must be a valid LC dentifier Value must be a numeric or character constant Escape sequences may be used in the constant The compiler translates the option directive to the form NAME DEFL value he value is optional as shown above by apearing within braces If the value is omitted the DEFL statement will default to a value of negative one i This indicates TRUE to the EDAS assembler The foption directive is used in LC to invoke a search o
28. e UO ee The point function ill return the statis of the pixel at the coordinate x y A return code of one 1 indicates that the pixel is ip on light while a zero indicates that the pixel is turned off dark _ the pixel contains something other than a graphic character a negative fe 2 is returned A negative one 1 indicates the point Xy is out of range The reset function will turn off the specified pixel while the set function turns on the pixel Neither of these two functions provides a return code unless X or y is out of range The pixel function can be used to point reset or set the pixel adit on the function code supplied as the argument pixel issues a return code only when the function code passed is indicative of point 2 or when an argument is invalid The plotting functions specified above refer to the arguments detailed as follows This function code specifies the erein to be performed on the pixel It can be an integer value in the range 9 25 If the argument passed is outside of this range the return code will be negative three 3 indicating INSTALLATION LIBRARY 4 23 LC LIBRARIES an invalid function code These codes are used as follows Indicates the reset function which will turn off make dark the pixel 2 1 Indicates the set function which will turn on make light the pixel M 2 Indicates the point function wh
29. example using pointers In certain cases during the use of pointer arrays indirection must be performed before subscripting into the data item Since subscripting takes precedence over indirection this kind of expression must be written as follows example arg char arg pointer to a T pointer array wrong way accesses third pointer instead of third character arg 3 right way zero s the third character of first string arg 3 0 SUBSCRIPTING Subscripting is denoted by a subscript in brackets following a primary expression primary expression subscript if the aag expression is an array name or a pointer to an array the subscripted expression returns the element denoted by the value of the subscript C arrays are subscripted from zero i e the first element in an array is numbered zero Function identifiers may not be subscripted A primary expression denoting an array of pointers to functions may be subscripted The primary expression must indicate the size of the object being subscripted char int pointer or the subscript will produce an error message For example x 25 3 is invalid EXPRESSIONS 2 15 LANGUAGE DEFINITION FUNCTION INVOCATION A primary expression followed by parentheses will cause the function denoted by the primary expression to be called Arguments may be passed to the invoked function by placing them in th
30. exclusive or BITWISE INCLUSIVE OR OPERATOR associative expression expression bitwise inclusive or U mR a WR m n m mm I gm e L L am Ld Lond a um ua LOGICAL AND OPERATOR groups left to right expression amp amp expression logical and LOGICAL OR OPERATOR a groups left to right expression expression logical or CONDITIONAL OPERATOR groups right to left expression expression expression Chie DE Thies na i ED GED CER eee eee SEF E ete See epee SS Ge Oe aum Eee ee Ao ee See eee ee eee eee eee eee eee eee eee a See MO SE Ce Se ee ee gee ASSIGNMENT OPERATORS group right to left lvalue expression simple assignment lvalue lt op gt expression compound assignment lt op gt is any binary operator except logical relational or conditional operators da GMNER GER amd sm Ae GNU SH up ae r ar VER p p ee ee sss uum es a oe nee p ee NND qunm p CURE PED p CON ue AU Um a m up ese cu 10 a a Um BINARY OPERATORS LANGUAGE DEFINITION The multiplicative operators take precedence over all other binary operators and group left to right When the result of multiplication overflows 16 bits the left most high order bits are truncated Since integer division is used the fractional portion of the result is lost The result of division is always truncated toward zero The modulus operator returns the valu
31. fp EOF if c putc c stdout abort Output file write error STANDARD LIBRARY 4 1 LC LIBRARIES GETCHAR This function is used to get character from standard input Its syntax is c getchar there are no parameters mue UA A d s NUUS ER GS aum UD ee 4e Amin a a DO Gm Gu CRT A dun Cim 4d um Qum Gum WW m di adum duda ccm es es es aum es asp Gump aum ee ee ee ee e nn SOR amm 4p URP xum duin GR SPA aum dum CHR GERD a 4A Me Sm que ame tala cum pA GeAA Ae WE dius VEND E XP deda XD um PR diea dan Gu qune PDA dh UT e Uwe chum VD amp TPR ue up ump dm me dum RP pP Gus URP URP cum him dpa num quam chum dpa cam cm ee Uum Aum Aum Um uin 4A uu 4m A Getchar inputs a single byte from the standard input Getc is used to perform the input x RETURN CODE The return code is the integer value of the character input from the ER file If an end of file is encountered then EOF 1 is returned WARNINGS 1f o is to be stored before testing for end of file it must be stored in an integer variable or the EOF value will be truncated to 255 EXAMPLE bytes lines while c getchar eof putchar c tbytes if c eol lines STANDARD LIBRARY 4 12 LC LIBRARIES GETSO This function fetches inputs a buffered line from standard input Its syntax fs eofind gets buffer buffer is a pointer to an 81 byte buffer
32. has already been defined in the module 65 gt argument error The expression just processed caused LC to input the next line before the function call was completely processed See the split function call error for additional information 66 gt bad label The label specified in a goto statement was not a valid LC identifier 67 gt expected comma The context of the input required a comma but none was found o l 68 gt function not declared The context of the input demanded that a function be declared i e the input did not match anything which could be a compiler directive or a variable gadi so it was assumed that a function was being declared 69 global symbol table overflow LC ran out of global symbol table space Either decrease the amount of memory reserved in high memory see not o enough memory error or split the module being compiled into smaller modules with fewer external variables 79 gt illegal address the amp address of operator was used with an expression which was not an object in memory 71 gt illegal argument name The argument name is not a valid LC identifier 72 illegal identifier The input was interpreted as an identifier but did not conform to LC s rules for identifiers 73 input file open failure An input file could not be opened successfully 7 3 invalid expression The input could not be recognized as an expres
33. heh Advanced Topics PPISESETTST TRE TTT ee utilizing Assemb1y Time Options TP wo q 1 POT OT ON oro oro o na Oo maana KA I 0 Co CO Gh Q U 4 WWW NPD Ni l 4 34 ucc 4 37 p ts Male Precision Operations Bosque TR S 7 4 00 ee ENSE E 4 43 C 1 ps a ee ES FORWARD LC is an exciting product for the TRS 8 series of microcomputers The power of the C language is beginning to be realized by many individuals LC puts the power of C into your hands The unique implementation of the LC EDAS language development system provides most of the standard C language capabilities as described by Kernighan and Ritchie in The C Programming Language as well as an extensive macro assembler LC has been under development for two years going through various transitions of implementation The product you now own has many unique features It will provide you with extreme fascination of new techniques in coding You not only have the opportunity of learning a relatively new compiled language but you also have the opportunity to instill advanced programming techniques into your programs You will get out of LC much more than what you give it If you are new to the C language take the time to learn it You will be greatly rewarded The tenure of the LC project has been intriguing That one word certainly does not sum up the entire history however No one word can Frustrating rewarding despair hope and many other words can be
34. if the pto address is less than the pfrom address the move will start from the beginning of the block If the pto address is greater than the pfrom address the move will start from the end of the block RETURN CODE There is no return code WARNINGS There is no checking on the magnitude of len thus a move with an erroneous value for len could overwrite a critical portion of memory STANDARD LIBRARY 4 14 i LC LIBRARIES ISALPHA ISDIGIT ISLOWER ISUPPER EEE E E E Z T E These functions are used to test a character Their syntax is retcod isalpha char retcod isdigit char retcod islower char retcod isupper char char x is the character under test isalpha is used to determine if a character is an upper case or lower case alphabetic lt A Z a z gt isdigit is used to determine if a character is a digit in the range lt 9 gt islower is used to determine if a character is an alphabetic in the range lt a z gt isupper is used to determine if a character is an alphabetic in the range lt A Z gt RETURN CODE a AA amp Oe Qu r ee YK 4m b Cm Each function will return a TRUE 1 or FALSE value based on the results of the test EXAMPLE df isdigit char printf Character is lt 9 gt n else if istower char printf Character is lt a z gt n else if isupper char printf Character is
35. in the LC language as a convenience to microcomputer users who are only familiar with hexadecimal The backslash may be followed by an x and one or two hexadecimal digits Either of these two methods result in an 8 bit character constant For example the character A can be represented as 1x41 using a hexadecimal escape sequence or as Ml1 in an octal constant Similarly to place a carriage return at the end of a line the following three methods could be used An example of a normal escape n An example of a hexadecimal escape Vx QD An example of an octal escape 1415 When a character escape sequence is used within a string the actual value of the escape sequence is stored in a string Gi e omy one byte of data per escape Thus the string An xgd M15 is only three bytes long in memory once the program is compiled and assembled CONSTANTS 2 5 LANGUAGE DEFINITION VARIABLE NAMES Tem na me dum AAA UA MO dim 4 a ae me XN NB Fam A AA t S eo UD mi The names given to identify variables ITEEIORE macros and labels are called identifiers and all follow the same rules as to their format LC identifiers may be of any length be practical and must start with an alphabetic character A through Z a through z with the rest of the characters in the name consisting of upper case or lower case alphabetic characters A through Z a through z numeric characters 9 through 9 or
36. indicates which control code is being specified Also certain characters that would otherwise be difficult to represent in strings and character constants are generated by following the backslash with the character These escape sequences are shown in the following table CONSTANTS 2 4 LANGUAGE DEFINITION Escape EE Sequence Control Code ASCII code used by LC S zss 25s2 gt 2S2 22 H E E 41 t 1 1 31 1 1 1 3 1 3 31 31 41 i l An AN NEWLINE ieee x 9D CR t T horizontal tab 7 x g9 HT b B backspace x ga BS r R carriage return x 9D CR MM form feed x gc FF OA backslash x 5C backlash qoM single quote x 2C apostrophe g null x U null byte ix double quote X 22 double quote uM su um GE du Cue CPP umm Gm 4mm Gm pv Gm Uu Cmm mE uma gt ce UHR GERD uma umm Cumas uma ui GER CES GER ums ums umm AES dumis dumm Jew umm D umm umm Cm Gi umm um Uu ee uum ee MR es GERD umm umm mE E m ME UMP cee Un Gum u ee A qum A AA COND Guam Gne Gee E uae ee Cun Cus ee auum es ee ese AD unis ee Conde eee ee ee 4S es ee es ane ee ane es A ee CUM ee cune duum CORR e es ED um mre In addition any binary code can be represented in a string or character constant by following the backslash with a numeric constant This is done by following the backslash with up to three octal digits An extension which is not normally allowed in the C language is offered
37. map agi tells pds that MYMOD MAP has the information needed to append the modu le Unlike in line libraries the order in which members are appended to a PDS library does not affect the functioning of the library EDAS continues to search the library until no further references can be satisfied by the library Thus members may be appended in any order purged and reappended etc a ous CREATING LIBRARIES MODERN TOPICS LC ASSEMBLY LANGUAGE OUTPUT STRUCTURE so ue w S up ap ow a gt or a qp Ar ee dep mp ee MER try mp e P GERD uum op CAVO UP y nb dep PA 306 Ze a BETS rrr tz sess AC generates a rather unusual assembly output file LC depends on certain macro s in the file LCMACS ASM which maintain and provide access to two separate program counters These macros allow LC to declare variables and define strings in the middle of a function without interrupting the actual generation of code to perform the function The macros also cause all variables and strings to be placed together at the end of the program These macros MUST BE USED if you are interfacing with assembly language to the variables generated in a module compiled by LC Failure to access variables using the macros will result in the wrong address being used LC PROGRAM MEMORY MAP mte B mp u Ans amp ami D Ama ee Aue mb ARS SUR no D pb D se aue ep e UMP me E UN e HUP Wm cue O um VP UR Hn Cup Cup oe T eSTART usually S2BH A rx
38. may be Found in appendix D ASM INTERFACING 5 15 ADVANCED TOPICS WHEN THINGS EU WRONG amar Wa que Se Ge Gh Gad ded Ge OF Ge Gee amp ee ee OO oe SS ee de m qus Qua an a a an o gt GR am CE ame ve m din din ob ah 2 dE GF Ge we c is language which offers great Flexibility but not without a price The price of C s freedom is the programmer s ability to make catastrophic errors with ease The programmer is not protected from himself when using LC Your best protection is to carefully check your programs when you write them for any evident errors before you try to run them Of course any time you test a program you should not have any disks in your drives that you would care about if they were suddenly erased This js not to say that you shouldn t experiment quite the contrary However ir be prepared for the worst With LC you have an Mi dtes over other LC RT an assembly language source file You can debug the program without second guessing the compiler or having to disassemble the compiled output The modularity of the program also helps Since there are clear interfaces functions to breakpoint at It would be helpful though not essential for the programmer to have familiarity with the 2 89 instruction set and with the Red dedii of LDOS COMPILATIC ON ERRORS e XD mb b Qr me Ab P w D mcm us generates an error message whenever it finds something in the input file that cannot be
39. move E p 2 i 1 y y h move p 1 i 1 break case 3 p 2 i 1 x xth move p 3 1 1 y yth move p 3 i 1 x x h move p 4 i 1 break case 4 p 1 i 1 y y h move p 4 i 1 x i move p 4 1 1 y y h move p 3 1 1 break return 9 HILBERT CCC D 6 APPENDIX SAMPLE PROGRAMS ye linetest ccc finclude stdio csh 4option INLIB main int x1 x2 yl y2 t tl I E puts xlc xlf clear the screen for x19 yl 9 x2 127 t0 t lt 47 tH line 1 x1 y1 x2 t l ne P x1 y1 x2 t for y2247 t 127 t gt t lne l xl yl t y2 line 8 x1 y1 t y2 mE exit P LINETEST CCC D 7 APPENDIX SAMPLE PROGRAMS xfer ccc s finclude stdio csh ye standard 1 0 definitions XFER copy standard input to standard output int c bytes lines FILE fp main bytes lines 9 while c getchar EOF putchar c Hbytes if c EOL lines fp fopen do w fprintf fp Xd characters Xd lines bytes lines rs XFER CCC D 8 APPENDIX SAMPLE PROGRAMS The following example program may help to illustrate the use call test define define _fdefine define define define define define define define define define foption int rc d The program was provided by Rich Deglin of syscall CKDRV 8X44B8 Note vectors are nove
40. must not access memory outside of the area allocated File access routines use alloc and free to establish and release File Control Areas FCA s The programmer cannot assume that memory not allocated is free for use since later file opens may cause memory overlays It is advised that the programmer always use alloc and free or sbrk for all dynamic memory accessing EXAMPLE symtbsz symtbsz symsiz make integral if symtab alloc symtbsz abend not enough memory glbptr startglb symtab STANDARD LIBRARY 004 2 LC LIBRARIES EXIT Erez This function is used to exit your LC application and return to DOS Its syntax is exit code code o integer return code Exit allows the user to exit cleanly from a program and control the consequences of exiting Passing a zero for the return code to exit indicates normal program termination causing exit to take the LDOS normal exit If a non zero lt code gt is passed exit will take the error entry into LDOS thus aborting any JCL processing in effect If the terminating program was invoked by the cmd function the value passed to exit will be the value returned from cmd An exception is if a negative value value is passed to exit in which case a negative one 1 is returned to cmd Exit closes all open files before returning to DOS RETURN CODE Exit does not return to the caller WARNINGS
41. of some of these files and their uses LC CMD This is the LC language compiler LC accepts as input C source code files and outputs an EDAS Version IV compatible assembly source file In order to organize files in a structured manner LC source code files have a file extension of CCC and LC output assembler files have a file extension of ASM E LC LIB Um m um Wb oW oum This is the standard function library It is an implementation of the portable library available under most installations of C compilers These functions allow programs to be written which will be directly usable under other C language systems that have the standard library available The Standard functions perform such tasks as input output dynamic memory allocation standard 1 0 redirection and string handling The standard library was designed to be compatible with the standard library under Western Electric s UNIX operating system FP LIB This contains the LC floating point function library LC does not have floating point variables built into the language itself However this library supplies access to the floating point routines in the TRS 84 ROM through functions Single and double precision arithmetic as well as trigonometric and transcendental functions are included FP LIB also includes functions for converting between ASCII integer single and double precision variables IN LIB The installation function library i
42. paws tase e vus viaa d re 2 21 not equal to R ee ee dd Pare db ice 2 21 bitwise AND Pad iae esueE LS UE AME E es eel J bitwise exclusive OR oooooooomo o aee ac eee 2 22 bitwise inclusive OR aida woe 2 22 logical AND dsid was TA 2 22 logical DR cece cca waite ss atau Shu oma cess puras COL conditional ere then else n Ped 2 22 ASSIONMONG aria id 2 23 y I X7 Cz gt amp eee 2 23 LC OPERATORS A 1 cm MT ML 4 wa APPENDIX OPERATORS ptr alloc nbytes ooooooooooooooo o were A2 retcod atod str dvar sss sss s ese ss scs see nn 4 43 retcod atof str fvar ssa ovas eve cuu ada Baas int Atoll dece Ji dad 4 03 retcod box funcod xl yl x2 ye Z corso uas Wed us 4 25 retcod call address Fegs 5 wid PER E R iS rera a RR 4 36 retcod circle funcod xl yl CL Vk A 4225 retcod cmd command string 3 2 34 96291 errr Tr 4 35 cmdi command string TTT Seda era 4 35 reteod CUFDOS S uauaest seseosn E sis 4 35 cEUurSOr TOW COT Ji vestes e A 4 35 retcod dabs Vl v2 liar a 4942 retcod dadd vl v2 03 44 4 44 v ore a rev s sees 4242 Gate S Ji vv reese e A 4 35 retcod dcmp vl v2 OTT 4 42 Fetcod ddiv vl v2 ase sesa sss a O ee SS DUI 4 42 retcod dfix vl v2 EE
43. recognized or that doesn t fit the syntax of the C language There are also some limitations in the LC implementation which can cause LC error messages to appear When LC outputs an error message it will print the line in error and point to the particular character where the error was recognized The actual programming error is likely to be earlier in the program depending on the type of error Some errors may not be detected until many lines later For example if a closing brace is missing in the input file LC will not be able to detect the error until the next function declaration which will then be flagged as a function call without an ending semicolon This is because LC thinks the previous function has not been completed Similarly if an opening brace is missing LC will not find dd until the last closing brace is encountered with no match In the appendix of this manual is a list of the error messages which LC can generate and some likely causes for each Most errors are usually typographical but the user should be well versed in the C language and the LC implementation Learn where to find information regarding syntax and capabilities of the language The language definition chapter of this manual n the appendix of the K amp R text are good places to Took when not sure of syntax WHEN THINGS GO WRONG ADVANCED TOPICS ASSEMBLY ERRORS There are few assembly errors which can occur if you assemble yo
44. stored in sixteen bits The short and long declarations are provided in the interests of portability The declarations int a short b Short int b2 long c long int c2 are all acceptable declarations and all result in the same size integer field This is acceptable since the C language does not guarantee that a long will be longer or that a short will be shorter than integers Integers declared in this manner are signed i e their most significant bit is regarded as a sign bit Their values can range from 32 768 to 32 767 decimal Unsigned fields do not have a sign bit They range from to 65 535 decimal and are declared like this unsigned u unsigned int ue Arrays of one dimension are allowed for short long int and unsigned types Pointer variables are different from the types described so far in that they normally contain the ADDRESS of a data item For example char cp declares a po nter variable named cp The asterisk denotes INDIRECTION i e that the data item is referred to indirectly through the pointer variable cp The address of the data item must be stored in the variable cp before it is used as a pointer to access a data item To refer to the data itself an asterisk is placed before the name e g cp denotes the data item An example of practical use follows DECLARATIONS 2 7 LANGUAGE DEFINITION char cp while E kein l eol amp amp c l EOF
45. the underline character C2 LC will accept an underline as the first character of an identifier however EDAS will not therefore Ge not start an identifier with the underline character LC remembers only the first eight 8 characters of an identifier SO these first eight must be unique Elsie is case sensitive i e recognizes the difference between lower case and upper case in identifiers Thus EOF eof and Eof are all different identifiers to Elsie However identifiers which must be written out in assembler source code for EDAS are converted to upper case since EDAS does not allow lower case assembly language code A good simple rule to follow is to use UPPER case for macro constants only and lower case for all other identifiers Since macro identifiers are not written to the assembly output file they will not conflict with any other identifiers which are the same except for case differences EE VARIABLES 2 6 LANGUAGE DEFINITION LC variables must always be declared before use The standard procedure is to declare variables at the beginning of the program globals and at the beginning of each function locals Character variables are stored in eight bits or a byte The declaration char c string 81 establishes a character variable named c and a character array named string Arrays of one dimension are allowed All other variable types short long int unsigned as well as pointers are
46. to fpinit by the user program will be necessary since fpinit MUST BE CALLED before using any of the floating point functions in the library It sets up certain data areas used by the floating point ROM routines and provides error recovery linkage FLOATING POINT LIBRARY 4 39 LC LIBRARIES SINGLE PRECISION OPERATIONS FETT TTT TTT The following functions can be used to operate on single precision fields length 4 Their syntax is as follows retcod frnd vl v2 vl rnd v2 retcod fsgn vi retcod sgn vl retcod fadd vl v2 E vl vl v2 retcod Fsub vl v2 vl yl v2 retcod fmul vl v2 yl vl v2 retcod fdiv vl v2 vl vi v2 retcod fabs vl v2 vl abs v2 retcod x fatn vl v2 vl arctan v2 p retcod fcmp vl v2 f compare vl to v2 retcod fcos vl v2 o vl cos v2 gae fexp vl v2 3 vl exp v2 retcod ffix vl v2 oe vl fix v2 retcod fint vl v2 f vl int v2 retcod flog vl v2 m vl log v2 retcod fraise v1 v2 yi yl tk v2 l retcod fsin vl v2 B 7 vl sin ve retcod frt vl 6 0 vl sqr v2 B ewm ftan vl v2 IE vl tan v2 a vi amp v2 are the address of single precision fields FLOATING POINT LIBRARY Y LC LIBRARIES These functions perform calculations on two single precis
47. two drive system your work files LC source and output files will need to be stored on this LC Data disk Therefore make a few backups of this disk to use for various LC programming sessions ET Notice that LC requires a two drive system If you have a one drive System you overlooked the machine requirements noted in the LC advertisements and in the catalog We would not want any user so frustrated with trying to utilize the LC Rer System on a 9in9te drive computer INTRODUCTION VUE E 16 you are real TEMA to proceed and create a working c amier a turn to the OPERATOR S GUIDE page 3 14 and note the simple exercise Place the LC system diskette in drive the LC data diskette in o 1 and Procerd with the PEE 6 Redd the rest of ihe acc user anial Pay particulis attention to Ce ie OPERATO2 S GUIDE and the LANGUAGE DEFINITION chapters Skimming is OK for ATE DEM but ret LE feel fer ce things can Pe ie in your LC a cm manu lal P uw vA e Done d i Have fun with Elsie 2 INTRODUCTION LET S MEET ELSIE ELSIE FILES gt m on A 0m 4m m 4m e ma amm rn cu URB d dur d AS ee Uum ou Elsie comes complete with everything you will need to turn your LC source programs into executable CMD programs There are many files on your distribution diskettes a compiler an editor assembler utilities libraries and JCL Poles Here is a description
48. unsigned DE lt HL UCMP o unsigned compare DE HL MTS l l ASR arithmetic shift right of DE by HL ASL arithmetic shift left of DE by HL e8NEG returns two s complement of HL eCcOM returns one s complement of HL eNoT returns logical NOT of HL eMULT multiply DE by HL to HL BDI VY m divide DE by HL returns remainder in DE quotient in HL dm ip am ae am E e B enh Gye ae GY oe ee oe oe i wag amm UR Wem a mr ma eee db TR nbs rr n m mr a m m e pt Br cu WD S Gm OCUPA Eph du de E dida es EPA EP UP MNA GENER i ue Pf i f AUFL A din ff inh ff fi Ep gabd AD ee Ge Cii mp Xs es A A MD FAM A TP cum A e E VERD A T BPK Gun A geb Cbr uum UEM um A ASM OUTPUT STRUCTURE B ADVANCED TOPICS ASSEMBLY LANGUAGE INTERFACING While it is possible to insert assembly language source code directly into your LC program using the fasm fendasm construct it is much cleaner to interface by placing your assembly language code into a separate module This keeps all the non portable code separate from the portable LC code It is best to call assembly language as a function rather than including it directly into an LC function by mixing C and assembly source code REGISTER USAGE All registers are available for use by the assembly language function The only stipulation is that the stack pointer must be returned in Ene Same condition as it was upon EUIS ARGUMENT PASSING LC passes argum
49. up as permanently attached to the keyboard and screen The REDIRECT switch overrides the ARGS switch if REDIRECT is ON e is also forced to ON S REDIRECT defaults to ON IVAR The ZVAR switch can be used to invoke the initialization of all variables to zero If ZVAR is not optioned only space will be reserved for variables and their initial values will be undefined Note that this switch EM may be turned off or on rpm the progran a ASSEMBLY OPTIONS 5 2 i S fo ADVANCED TOPICS SEPARATE COMPILATION hard had NP b ae Am Gm ESS E E E E LC supports separate compilation functions and modules can be compiled at different times then assembled together to produce one program This facilitates the creation of compiled function libraries and results in great time savings Commonly used functions can be compiled once then only assembled into new programs without recompiling Large programs may be segmented and each segment compiled separately then assembled as a whole With the extern and static statements the variables used in a module may be specified as external or local When separately compiling modules which reference variables in other modules two approaches may be taken to supply declarations for the shared variables The global option of LC may be turned off and on so that only one module actually defines the space for global variables The other method which is the pr
50. 13 LANGUAGE DEFINITION allowed in many implementations because they are expecting an arithmetic assignment Even if some BASIC s allow it it is best not to do this type of assignment in order to keep programs relatively portable Another situation is shown in PASCAL IF A B lt C THEN BEGIN where the PASCAL compiler expects a boolean expression between IF and THEN Even if A is a boolean variable this assignment is not allowed in most PASCAL compilers This is not intended to denegrate PASCAL There are good reasons why the authors of PASCAL did things this way However the C language does not draw distinctions between types of expressions within the context of the program The distinctions are made in the types of operators instead PRIMARY EXPRESSIONS The E anieh are manipulated by operators in an expression are called primary expressions The basic elements which make up a primary expression are identifiers constants and strings Identifiers are the names of variables and functions Function and array identifiers effectively resolve to the address of the function or array while all other variable Identifiers resolve to the contents of the variable Constants are character or numeric decimal hex octal values Strings resolve to the address of the first character of the string The operators which LC provides for stating primary expressions group left to right This means that the left most operator is inte
51. DATE 8xX4479 DODIR PX4463 DSPLY 8X4467 TIME Px446D AF BC 1 DE 2 HL 3 IX 4 IY 5 CARRY INLIB char regs 61 buf 109 main put s Test of call QN n for A d P d lt 8 d regs BC d rczcall CKDRV regs printf Drive Xd XsXsWMn d rc not ready if regsLAF J amp 1 lt lt CARRY i waitO nem is write protected n dt DATE Date dt TIME Time regs HL Je This is a message n call DSPLY regs wait E regs BCJe 4 8 99 regs HL J buf call DODIR regs strmid buf 8 buf 9 8 strmid buf 99 buf 8 8 printf Xs Xs free XdK Wn buf 8g buf 99 bufL 18 J buf 19 K 8 regs BCJ call DODIR regs wait wait puts AnHit any key getchar clscrn dt addr str char addr str regs HL J buf call addr regs regs HL J 0 printf s s n str buf clscrn puts xld xlf return 8 1 SYSCALL CCC m E D 9 of MM A A AA A A A KA m A KA NS d I UN eu to ee BETT Sey sg NP T oe E Fr L t U r i A 0 J i e T L i v l v l l i E s S S N 9 i 1 5 z i d is B DE ad i w ig lt 4 x Y s id D po it t 3 s s Tae B oe i 2 CE M E PETI ON s N V Lie yee a eens
52. EE 4 19 retcod freemem 3 uo sa Eu nese ka be UE p RR e 4 34 retcod frnd Vl V2 Da 4 49 retcod a UT E E A A 4 40 retcod ONE AP ect 4 40 retcod fsqr vl v2 ss m e sasa aaaea T 4 46 retcod fsub Vl V2 J airada 4 49 retcod ftan vl v2 5 eee O Y se 4 49 retcod ftoa fvar str ccce wocccceee 4 43 retcod ftod fvar dvar ccccccceccces Q 4 43 LIBRARY FUNCTIONS B APPENDIX OP ERATORS intval ftoi fvar bo n s Den Ra eeeecee ee 4 43 getet TU rerien 1 ceeds esse RR EERE VERS wee 4 11 s ge tchar i ssevasastseo ces eps aos ele sof ind gets buffer E T E ET ETT 4 13 retcod inicr TERME TAE H P 4 34 Fetcod inport port x s se aaee uw eras ch er ous 47524 retcod isalpha char eere ies D L retcod isdigit char cesses essen seas eere 4 15 retcod islower char 4e a VR ETE CRT EET TS 4 15 retcod isupper char dd rci es semana 415 itoa int decs qa ens 4 93 retcod fitod ivar dvar ssa sss aasa aeaaea PON 4 43 retcod itof ivar fvar oiocorommmcoosscmoncanoonss 4 43 itox int hexs Dj sese sneer ABS pa retcod line funcod xl vl x2 y2 i inn 4 25 i move pfrom pto len oooooomm oomoso ueri 4 14 outport port value sss sss seene Lees saw V Eee id E 4 35 retcod pixel funcod x Y ie e oro so 4 23 ploc address siria dais
53. ENT break Break is used to exit any while do or for loop and to exit the body of a switch statement Whenever a break statement is encountered execution immediately goes to the next statement past the loop or switch statement Break is illegal outside of any loop or switch compound substatement For an example of the use of break in a switch statement see the section on switch case mes strscan c s char c s find Dad c in string s while s c if s break end of string v tts next character return s STATEMENTS 2 28 LANGUAGE DEFINITION CONTINUE STATEMENT continue The continue statement is used to skip the remaining statements in a compound loop substatement In a while or do statement execution continues at the test expression In a for statement execution continues at the reinitializing expression the third expression The continue statement is illegal outside of any loop statement convert to lower case while c getchar eof if c A ll c Z not an uppercase character hi doesn t apply tolower c Such artc P2 RETURN STATEMENT return return expression The return statement causes the currently executing function to end If an expression is provided then the result of the expression is returned as the value of the function The returned value is undefined if no expressi
54. LC programs begin execution here Re aa 5 Bene modules user assembly language EM T e a e Lo an Tavs functions from LC LIB FP LIB ep IN LIB STORG d Program variables and strings generated with EE l macros EN PROGEND gt er mE LE y ES Te A Pa ea fe RE Oa e ae ONE Eis ele Memory allocated by sbrk In use by the program aM or maintained by alloc and free m eLOMEM IM y o ic so toa aris A LU ERN RR l Unu sed memory available from alloc or sbrk SP 1024 LC program stack local variables stored here 1924 bytes of unused space LC always reserves 1K for the program stack when requests for dynamic puc allocation of memory are made HIGH 2 88 S ae e FE 100 0 AF SN amp W anm e Gh UNT QUA amp UMP SUP h A mp me b amp Uo Qu o a f AP oF CF uh om UL ue a um amp P uh P uh SED up GEM Aue A P UU ASM OUTPUT STRUCTURE i ADVANCED TOPICS LC MACRO Krz It is important to understand how to use macros in order to directly interface to variables declared by LC programs However it is not necessary if you are writing a function which will not access LC declared variables For more information on the use of the EDAS macro capability see chapter six of the EDAS manual The macros in LCMACS ASM are as follows SORG switches the EDAS program counter to the variable storage area The current executa
55. N LIBRARY 4 27 LC LIBRARIES address can be passed v a ploc so that the plotting functions plot into the buffer The buffer could be subsequently moved to the CRT image area with the move function RETURN CODES X Return codes are provided by the pmode function where applicable These codes are indicative of the following i ae Indicates the current quadrant in effect when a pmode g function is invoked 1 Returned if quadrant is not in the range 8 4 INSTALLATION LIBRARY m 4 28 E LC LIBRARIES STRING FUNCTIONS The most important bit of information to convey at this point concerning the use of strings and khe C language is that the language provides no internal mechanics for dynamic string maintenance Strings are generally stored in character arrays arrays are fixed in length at the time of their declaration Therefore when you employ the string functions contained in this installation library remember that your application must provide the proper array sizes to deal with the expected lengths of the strings Where string lengths are indeterminate at the time the application is coded but are determined rather at run time it may be prudent to consider testing the length of a string operation result prior to actually performing the intended operation to ensure that the operation will not exceed the array size of the array receiving the string result Another point worth rememberin
56. NDIF IFREF FUNCB SINVORE IT DEFL 1 Get it ENDIF I IFREF FUNCC INVOKE IT DEFL 1 Get it ENDIF Xm j E anon invoke the cdi if needed z Nek IF SINVOKE IT THE MODULE GOES HERE ENDIF With the construct shown above the module will be assembled if any of the functions are referenced It is better to separate the functions into separate modules if possible c E An in line library is searched by EDAS sequentially from beginning to end Therefore the order in which functions are placed in the library becomes important If a function in the library is called by another function within the library then the calling function must appear first This is because the IFREF for the called function will not be true until the calling function is assembled So the generat rule is Calling functions first called functions last PDS ERES The libraries which come with the LC compiler are actually Partitioned Data Sets PDS A PDS is a file which is partitioned into individual members The Partitioned Data Set PDS utility available from MISOSYS is CREATING LIBRARIES M ADVANCED TOPICS used to create and maintain PDS libraries PDS members may be executable commands data files source files etc In the case of the LC libraries each PDS member is an assembly source module EDAS searches PDS libraries by performing an IFREF check on each member name Only those members which have been
57. ON Some examples of if statements df x4 9 x x absolute value of x if i lt ix b a compound statement else i and an else clause nested if statements if past twelve if before six say good afternoon else say good evening else say good morning SWITCH CASE STATEMENT switch expression lt switch_ statement gt coe Switch statement statement case constant expression P Pis default aa f m EN The switch case statement allows program execution within the switch statement to be determined by the case and default prefixes The expression in the switch statement is evaluated first then if any of the constant expressions match the result execution begins immediately past that case prefix If none of the cases match the result and there is a default prefix then execution begins at the default prefix Otherwise when no matching case is found no statements in the switch statement are executed The switch case statement MUST have a compound statement as its substatement This is the only case where this is true The default and case Statements may occur in any order within the body of the switch case However A CASE OR DEFAULT MUST PRECEDE THE FIRST STATEMENT in the switch case If this is not done none of the cases will ever be executed LC limitation LC 1 a requires that the default must be the last prefix in the switch case default constru
58. RRR RR RKR KR K FBIS E A RES OFPLIB sss aree RRR RRR RRR RER KBECHO totor rosoncrnorasososrcrncaannn non Ec MAXFILES po ve vv P cence se REDIRECT WG ia Rew ks PX eve ONS ONS coa eee nr reduc EAR eee E RI ESTIS ere er AER ACA noes E anie Compilation teretes ne nennen tent 3 Using the Global Option X a e Z s qeusesec mers lt lt Using Extern and Static e R e sS K Ka ees R Ree Assembling Separately Compiled Modules DENS NE Creating User Libraries A E senos dass Soe ine tne Libraries serves sce res cos aed o0 094055 POS libraries uao one e ese sn cere bai Assembly Language Output Structure MIDI Program Memory Map eeoeteeeccoocecovsveeececsottell V EC Macros metet deles a LOC Identifier Output i A 2 llle e ce ee Lou es Cu p RUM Time SUbroutines xK Nea T ce cg s C Z d axe cva ale TE d e rd Language Interfacing cases g eg sad geas saa Of E EA Register Usage xy ee cr TOT EC lt Argument Passing Werecesssecssovocscosoevevesoco oe re Labels and Constants eecotoseececootooevvoceose k When Things Go Wrong eaae KaK RKR Kae Rene eL OM Compilation Errors ias odas D Assembly Errors oca code Apenas A Nx TT E IE Operators oso 1k Ua AN Ka rada P E Re Library FUNCTIONS 06 2 44e ces ves Qs we ve ese LPS PET ro ide Error Messages then enhn Second Edition 1982 Double Precision Operations s x x K rn Data Conversion Functions d Ys sss ss s
59. STANDARD LIBRARY dip ecce LC LIBRARIES TOLOWER TOUPPER These functions are used to convert a dd from one case to the opposite case Their syntax is tolower char c toupper char char is the character under test C EE is the converted result tolower is used to convert an upper case character lt A through Z gt to a lower case alphabetic lt a through 2 toupper performs the Opposite function a lower case character is converted to upper case Both functions affect only alphabetic characters numbers special Sys etc are Teturned unaltered RETURN CODE a ou db ub sg ap oe a GU uw GN Each function will return the converted character as required STANDARD LIBRARY 4 21 LC LIBRARIES INSTALLATION LIBRARY ame dei a ah ads din C A abis S alie de du An du amp du EP dup d m alm aum Oe Aie A cmo O Ai Ain CUP alin oe dup Ae du 4m r The installation library is a collection of functions very specific to the particular machine LC is running on Also included are functions not considered to be standard C functions These functions group themselves into STRING functions PLOTTING functions and CONTROL functions All of the functions are contained in the library IN LIB note STRCAT STRCMP STRCPY and STRLEN are documented under the string functions however since they are standard C they are physically located in the LC LIB library If your LC
60. TING FUNCTIONS mifIEEPISBeTTISTEATSTIEEZzEITITTT These functions are used to plot geometric shapes lines rectangles and circles Their syntax is as follows retcod box funcod xl yl x2 y retcod circle funcod xl yl rl retcod line funcod xl yl x2 y2 funcod a an operation code to set 1 or reset 8 the pixels involved in the geometric plot x1 yl the coordinate of the first point defining the geometric shape xe y2 the coordinate of the second point defining the geometric shape rl the radius of the circle in y units The line function will plot a line connecting coordinate point xl yl with coordinate point x2 y2 E The circle function will plot a circle at coordinate center point xl yl of radius rl The integer value rl specifies the radius of the circle Since block graphics are generally taller than their width it is necessary to specify the radius in units of either x or y Within these plotting functions rl is a value representing the radius in y units The box function will plot a rectangle around the diagonal specified by the coordinate point pairs xl yl and x2 y2 If the coordinates specified either equal x xl x2 or equal y yl y2 then the rectangle will diminish to a line The rectangle will collapse to a point if both xl x2 and c NE VIRTUAL POINTS p mp CD UE S SD Gub O UD UG es amp uA The concept of virtu
61. You should get into the habit of using the TAB key right arrow to organize your LC code into neat indentations It will be shown below as lt T gt Follow the line numbers shown below with the text as found in K R i P ET EDAS YOU TYPE 9g1gg include stdic csh lt ENTER gt 99119 maint copy input to output ENTER 99129 lt ENTER gt ggi3Q0 lt T gt int c CENTER 909149 lt T gt while C getchar t EOF ENTER 99159 lt T gt lt T A lt ENTER gt 089169 lt ENTER gt 00179 BREAK a gt w clone d lt ENTER gt d specifies the drivespec New file D ZEN gt b LC OPERATION 3 18 OPERATOR GUIDE You h ve just entered an LC program saved it under the name CLONE CCC d and returned to DOS Ready Now enter the command with d representing your drivespec DO LC FILE CLONE d If you have entered the program correctly LC should compile your program and invoke its assembly to create the EEE file Try out your program according tok R If you want to start understanding the concepts of 1 0 redirection turn to page 1 7 of the INTRODUCTION The program you have just compiled into an executable CMD command is used to illustrate I O redirection Try out the examples shown 555555522222255002 5 4XXXXXXXXXXXXXXXX 0022222 lt lt lt lt lt gt ATTENTION lt lt lt lt lt gt gt gt gt gt lt lt lt PIO EN If you are inv
62. a list of characters within single quotes apostrophes For instance the character constant A is stored in the computer as the number 65 in decimal Again it is up to the programmer to assure that the number of characters between apostrophes can fit into the variable being assigned If more characters ae EE than can fit only the last one or two as needed are used it we o LV ur When a sequence of characters is needed a STRING can be specified by enclosing the characters between quotes sometimes called double quotes i e This is a string LC does not place all of these characters into a variable but rather the ADDRESS of the first character of the string Thus when the string testing 1 2 3 is used in an LC program the characters between quotes are stored in memory and the address of the first t is used in the expression where the string was specified You can say that the number generated by LC to represent the string really POINTS to the string The subject of POINTER variables which are handy for ron REMOS will be discussed later There are certain control characters that are needed frequently in programs but which differ from machine to machine These can be represented in C programs using ESCAPE SEQUENCES to provide a machine independent const nt The backslash character V is called the ESCAPE CHARACTER and deno s the beginning of an escape sequence A letter following the escape charecter
63. added to the list During LC s long labor Jim s wife Sam had some of her own giving birth to a new daughter Danielle The encouragement and support that Jim s family provided him shall not go unnoticed let alone the deep understanding of all those late hours at the computer A special thanks goes out to Rich Deglin for his continued support throughout LC s design and implementation life cycle Rich is also remembered for his contributions to the installation library of the string and control functions and his many suggestions of enhancements to the standard library I d like to point out that Karl Hessinger s plotting functions will be used by many LC programmers and will be most appreciated To Jim Frimmel goes unending appreciation for a job well done This astute mind has formed many of the sophisticated techniques inherent in LC It has been my personal pleasure to have worked so closely with Jim over the long LC development time frame It will be equally pleasurable to continue this association Jim s efforts were sparked by the work done on the SMALL C compiler by Ron Cain one who has certainly provided the foundation for a lot of C work Lastly let me acknowledge the understanding that my wife Brenda has demonstrated Those long hours spent in putting this reference manual together were time apart from her For a newly married couple it was a noble sacrifice It will not be forgotten Ney Ae Publisher
64. al The compiler regards the declaration as if an extern statement preceded it STORAGE CLASS 2 11 LANGUAGE DEFINITION External declarations which do not have a storage class declared are special entities They belong to the implicit class external and may be referenced from other separately compiled modules which declare the variable as extern E STORAGE CLASS 2 12 straight LANGUAGE DEFINITION EXPRESSIONS Gs m m E oa One of the most powerful features of the C language is its expression capabilities The amount of work that can be done by one expression is sometimes mind boggling A quick example end of file c getc file EOF fclose file count This convoluted statement will get a character from a file and place it n the variable c The character is compared to the value eof which indicates end of file the result true or false is placed in the variable end of file Finally if it was the end of the file the file is closed Otherwise a counter variable count is incremented to provide a count of the characters read The example was a bit exaggerated and expressions this complex can be quite hard to understand Two statements must be made about the complexity of expressions in the C language The programmer who does not fully know and use C s expression capabilities is seriously handicapped unable to use the full power of the C language On the othe
65. al points is an important one What it means is that your plotting routines do NOT have to limit themselves to the CRT image area For example a circle 1 8 0 28 function describes a circle about the origin This means that a portion of the circle would be plotted off of the CRT image The plotting functions permit your arguments to describe such virtual images however any portion of the geometric shape that would be outside of the CRT image area is inhibited Thus in the above example only a portion of a circle an arc will be plotted INSTALLATION LIBRARY 5 LC LIBRARIES It is also important to note that if any virtual pixel is debi in your arguments the function will return a negative one 1 after completing the entire geometric plot Your program can mare use of this return code if it needs to detect this fact RETURN CODES Return codes are provided by the above functions where applicable These codes are indicative of the following E Indicates that the dord hite sotni xl yl x2 y2 or a portion of any plot is out of range i e virtual and does not appear in the CRT image 3 Will be returned if the function code passed is invalid not in the range 2 1 EXAMPLE The following routine will plot increasing rectangles starting at the center of the CRT image n for x1 63 yl 23 x2 64 y2 24 xl gt al x2t oer box l xl yl x2 ye LEE Try out the next example program
66. all C language installations Programs written using functions in the standard library are easily transported to any other computer supporting a C language system with the standard library implemented The most important aspect of the standard library is that it allows the details of each system s peculiar operating environment to be hidden from the programmer s view The standard library provides the functions for input output memory allocation and character set manipulations In addition a collection of subroutines used by the compiled C program to perform basic operations is also supplied in the standard library Users can also create their own collections of often used functions that can be used in the same manner as the standard library These USER LIBRARIES reduce the programming time compilation time and program complexity necessary in creating new programs Functions once defined written ard tested can be added to the user library and need only be referred to by name in later programs The linking process brings the functions into subsequent programs without the need to recompile If you want to create and maintain your own libraries you will need the Partitioned Data Set PDS utility Special purpose libraries may also be created for use in particular types of applications For instance the functions specific to the TRS 8P are provided with your LC package are in the special purpose library IN LIB This is an exam
67. am ome tor toe toe tee tee gem UM dm te jm te ee tee Hp cu te ee UNE A GEN ee du ee es ise RENE Ge ius e CURA XAR ugue es ipe ise ju ju Hp S PP dues te ies tee HL UST dus ee es iem due A A iue VEA iuo NUES Sev NR uw Gets inputs a line up to 89 characters long from the standard input and places the line in memory starting at the address given by buffer Fgets is used to perform the input RETURN CODE The end of file indication eofind is the return code eofind is NULL if an end of file is encountered otherwise eofind is buffer WARNINGS The buffer must be at least 81 characters long STANDARD LIBRARY 4 13 LC LIBRARIES MOVE This function will copy a memory block in memory Its syntax is me 4 CA ae OF QAM UU HS UA AP RUM E GENE ee UNE ee A UD RAD ARA ue As GU GA Uh hue GP A As EE T W GS PEN oe GP As PAN As H oe Chu um e RES RES RE Ow AA EE GE RP OF Gn A OF UN dH Ve due a move pfrom pto len pfrom the address of the block to be moved SL i ZEN l pto the address of the block s new starting address len the length of the block in bytes l 4 SUS ques UD on CUR UM UU umb cu ee AED ee Gs UU nde Ape ud GU GU ae SUE Gas VA SUL AED GA Gm CU GER GU xm V4 quu AUD a oe a a cam a OH dud Ape det VD Vp RED QM VAR Gas A AUS QS ae ee AUD UNS de This function will perform a nondestructive move of a memory block That means that
68. ample nl P is a simple statement However the statement h h 2 xO h 2 W yPth 2 x xO i 32 y yP 19 u x3 v y i pC l i 9 is a compound statement STATEMENTS 2 3 LANGUAGE DEFINITION DATA REPRESENTATION CONSTANTS ee cen m at Ge a r ar Cm Gu Um Abe Uu ee a a aue SP ow Gui Gub oe sum oe Numbers and characters nae be entered in your LC program in certain ways in order for the compiler to understand them perm A fixed value to be used in an LC expression is called a CONSTANT Where just a decimal number is required you can enter it just as you write it A leading zero indicates that the constant is in another base A leading zero followed by a string of digits indicates an OCTAL CONSTANT A leading zero followed by X or x indicates that a hexadecimal constant follows Thus the decimal number 255 can be represented as peut or PAS as desired qf the variable to be assigned the constant is not big enough to contain the constant only the least significant bits LSB of the number are stored This is in effect storing the remainder of dividing the constant by 256 or 65 536 depending on the variable size No warning is given when this happens SO the programmer Ns be sure WIRE variable can hold the number a CHARACTER CONSTANTS mm a way to specify the code for a character which does not depend on any particular character set A character constant is
69. ample LC program that illustrates the straightforward use of standard I O redirection The following program can be used to copy any file to any other file remember that file can be any device or LDOS disk file CLONE copy standard input to standard output finclude stdio ccc int c main while c getchar EOF putchar c The example program simply copies the standard input to the standard output until end of file is reached Once this program is compiled and assembled it can be used to copy any file to any other For example a CLONE lt CLONE CCC will display the file clone ccc on the system console The command CLONE gt PR lets the user type to the system printer If disk file copying is needed the command CLONE lt INFILE ASM 1 gt OUTFILE BAK 2 will copy the file INFILE ASM 1 to the file OUTFILE BAK 2 If tne user wishes to have a printed log of any error messages that a program puts out use Something like AC TESTLIB PR Any messages that LC outputs to the standard error file will be re directed to the printer device in lieu of the console display INTRODUCTION 10 7 LET S MEET ELSIE STANDARD HEADER FILES E E E Standard header files are files which contain definitions peculiar to a system They usually take the form of define statements and extern statements within the header file In order to use certain libraries a corresponding header file should be
70. and software to bring Elsie to you His artist s eye also gave this manual the friendly feel and utility that his products are known for What makes the Elsie package especially unique is the work that Roy put into the EDAS IV assembler This assembler is the best example of user driven software that I know of Roy listens to his users and responds and he has gotten quite an earful from me Most of all he has been more patient than I could have imagined waiting for my perfectionist dreams to become useful reality Roy s bride Brenda has displayed this same patience and kindness with nary a protest I m sure many others are with me when I say thank you and may God bless you both Elsie has been helped along the way to becoming a product by some good friends Karl Hessinger and Rich Deglin were especially generous with their time and programming skills Steve Hill and Scott Loomer also helped with suggestions advice and feedback Also my wife Sam s editorial skills have resulted in an unusual combination sound grammar in a technical manual To all of you who have helped Elsie along thank you and may God bless you To my new daughter Danielle Michelle who like Elsie is full of bright promise and laughter Ex September 20 1982 zd e PREFACE Although considerable effort was expended to make the LC reference manual as complete as possible this documentation package in no way is to be considered an
71. ard library automatically opens these standard files They are also automatically closed when the program is exited as well Thus the program which uses the standard I 0 files exclusively can deal with input and output and leave the opening and closing to the LC standard library INTRODUCTION 1 6 LET S MEET ELSIE STANDARD 1 0 REDIRECTION TS SRS SST SSS SSS TSS STS SSS SS The standard 1 0 files normally operate to and from the user s console However a facility is inherent within the LC standard library to permit you to re direct any of the standard I O devices thus the term I O redirection The user can give a file specification that will be used in place of the normal specification when a standard file is opened This is done on the LDOS command line when the user executes the program When the left angle bracket symbol lt appears on the command line followed by a file specification that file specification is used when the standard input file is opened Similarly the right angle bracket symbol gt causes substitution of the standard output file specification the gt gt causes standard output to be appended to the redirected file device and the number sign symbol causes substitution of the standard error file specification Spaces are NOT permitted between the redirection character and the file specification It may not be immediately obvious how this feature can be used Here is an ex
72. are created and placed on the stack so that the user may access them from main If turned OFF some savings in memory result as no parsing of the command line is done ARGS defaults to ON For more information on argc and argv see K amp R FIXBUFS This option if set to ON will cause standard 1 0 to pre allocate all buffers needed for standard I 0 This eliminates the need for the dynamic memory functions to be loaded and prevents users from locking themselves out from further fopen s by allocating all of memory This also guarantees that the standard I O files can always be opened if the program is loaded When dynamic allocation fixbufs is off is active a program once loaded may not be able to allocate enough memory to open the standard files resulting in an error message and an abort l FIXBUFS defaults to OFF Whenever the floating point library is to be accessed this option MUST be specified It controls the initialization to the 80 ROM as well as the searching of the floating point library For this reason it must be included in EVERY module which uses floating point However it must never be turned OFF by a module This wil result in undefined symbols at assembly time if it ASSEMBLY OPTIONS 5 Mladi dad was previously turned ON This option may be ured ON by the graphics function in the standard library FPLIB defaults to OFF to avoid unnecessary HM and Fabia P KBECHO at A D In ce
73. aster for larger libraries The creation of an in line one after another library should go something like this The user types the following commands EDAS YOU TYPE I ENTER NOW IN INSERT MODE 90190 IFREF FUNCA 9giig lt BREAK gt m EXIT INPUT MODE 0 2 LFUNCA LOAD THE FIRST FUNCTION Ds B UU INSERT TO BEGIN AFTER LAST 02430 ENDIF 82449 IFREF FUNCB 2459 lt BREAK gt BREAK TO EXIT INPUT MODE 0 LFUNCB LOAD THE SECOND FUNCTION COE KG aug ENDIF 94420 BREAO HIT BREAK TO EXIT INPUT MODE gt WUSRLIB 1 SAVE THE LIBRARY ON DRIVE 1 CREATING LIBRARIES 5 5 ADVANCED TOPICS Any number of functions can be added in this fashion by appending to the existing library Ear function could also be edited separately and then appended together wit 1508 APPEND command use the STRIP parameter of APPEND to remove the EOF byte X 1A from library when you are appending another module This process Knee TEES which looks like this IFREF FUNCA FIRST FUNCTION ENDIF IFREF FUNCB SECOND FUNCTION ENDIF AND SO ON A different approach is needed when several functions have been compiled together in the same LC invocation A temporary label is needed to control the invocation of the module This type of construct looks like this INVOKE IT DEFL 0 Default to no invocation IFREF FUNCA SINE M DEFL d Get it E
74. behavior is the same as that of external variables their scope is more limited however Static variables declared outside of a function can only be accessed by functions within the module being compiled Other separately compiled modules cannot get to them by declaring them extern Static variables declared outside of all functions are accessible to all functions within the module Static variables declared within a function are similar in scope to auto and register variables They can only be accessed in the block in which they are declared Thus two static variables with the same name may be declared in different functions Functions may also be defined as static making them only accessible from within the current module However since LC is a one pass compiler the definition of a static function must precede any reference to the static function This is because the compiler assumes that an as yet undefined function is an external function STORAGE CLASS DEFAULTS When a variable is declared by only stating the storage class auto xl register x2 extern x3 static x3 the variable type is assumed to be int This is a perfectly acceptable shorthand way to make integer declarations When the declaration of a local declared within a function variable has no storage class LC assumes that the variable is an auto variable A function declared within another function body is assumed to have a storage class of extern
75. bject is specified by placing the class name in front of the normal declaration auto char c static int aiL203 STORAGE CLASS AUTO Variables which are declared auto are stored on the Stack This is the default for variables dec ared within a function so the declaration may therefore be omitted Local variables which are auto are created afresh each time the function in which they are declared is called This allows functions to be reentrant and recursive Functions may not be declared with class auto since a function must be declared outside of any other function AS KER say the C compiler is incapable of compiling code onto the stack The scope of an auto variable is the block within braces in which it is declared All other portions of the code being compiled are oblivious to the existence of the auto variable and in fact there may exist other variables with the same name o The auto class is illegal for functions and other external definitions any variables declared outside of a function STORAGE CLASS REGISTER Variables declared in the register class are regarded as auto variables by LC since the 2 89 has no extra registers available for use as register variables Register variables are stored on the stack in the same manner and are also illegal outside of function The scope of register variables is the same as that for auto variables STORAGE CLASS EXTERN e URP ey wab Ge I Gp wap
76. ble program counter is saved in TEMP to be restored by a PORG macro Anything assembled by EDAS after SORG will be placed at the end of the program past all code assembled in the PORG normal sections This macro recovers the original program counter saved by the SORG macro The variable storage program counter is also saved so that the next SORG will continue where the last left off WARNING a PORG must follow a SO0RG only not another PORG The proper program counter will be lost if a PORG is done when not in the variable storage area VAR fNAME SIZE All external variables are declared by LC using the VAR macro A data area will be defined which is designated by the NAME given with the SIZE given Any references made to variables declared with the VAR macro are made using the following macros This macro is used to prepare for the definition of a string The HL register pair is loaded with the current storage program counter and the EDAS program counter is switched to the storage area counter The program counter must be in the program area before the LSTR macro is used LDS NAME This macro gets the address of the variable NAME into the HL register pair ASN OUTPUT STRUCTURE 5 9 ADVANCED TOPICS GETB NAME This macro fetches the contents of the character variable NAME into the HL register pair The H register will be loaded with zero and L will contain the character
77. cations take the form of X xxx yyy char As can be noted the R fication is a sequence of sub fields of which the percent sign X and the char are mandatory The percent is an escape character signaling the start of the field specification The char denotes the format of the output field image binary decimal string etc The sub field specifications are interpreted as PBT HHS L4 the mandatory specification initi ator specifies that the value will be left di within the print field image Xxx lt specifies the minimum width T field image yyy specifies the maximum number of string bytes to print char the conversion character b binary o octal dedecimal xe hexadecimal s string c character u unsigned Any porttan of the control string which cannot be interpreted as a conversion specification field is considered to be transparent printing characters and will be pes des to the print image EXAMPLE printf Xd characters Xd lines were copied n bytes lines STANDARD LIBRARY 4 16 LC LIBRARIES a a ae ae ae an am ae CU ae This function is used to output a character to a file Its syntax is a cret putc c fp c 5 js the character to be output mE E fp is the file pointer for the output file 7 ar due up COND UND ae CURA a a eae ae ow ow Vi ee ae Ce O ee d DO DO pe ee y up cg MD ee O 9 QUAD CONDO O O Se O unm O GN GP GER oe
78. ce code directly within the LC source file It should be used ONLY when it is ABSOLUTELY necessary to write a routine in assembly language Remember any LC source code file that has imbedded assembly language code is generally NOT portable The more assembly language code you imbed the less portable your programs become and the more you have to recode when transporting your program to another machine All input past the asm statement is passed unchanged into the output file Of course since the output file is an assembly language source file the statements following the fasm should be assembly source statements The block of assembly statements is ended with the endasm statement Please note the fendasm statement must be the first thing on a line other than tabs and spaces Otherwise the fendasm will not be recognized and the C source code following the endasm will be passed uncompiled to the output file This escape to assembly language is provided as a convenient kludge mechanism only It is not intended to be the normal way of interfacing assembly language functions to aC program The proper way to interface to assembly language is to place the assembly function in a separate module perhaps even in a user library if it is to be used frequently This makes the program easier to transport to other systems as the machine dependent code is separated from the program source See the Advanced Topics chapter for more informa
79. character string SOURCE This also represents a pointer to a string which is used as the source Siro where the function requ res more than one string in its arguments POS This represents a starting position relative to the beginning of a string It is essentially used as an index or subscript into the character array 9 lt POS lt n l This parameter is used where required to indicate the length of some substring In the case of strept it is used to specify the replication quantity REM CODES i The return code of stremp is lt 9 or gt P as noted above The return code of strien is the length of the target string The functions strmid and strepl will return a negative one 1 if the arguments specify a resulting position outside the range of the string For instance if strmid s error 6 3 printf String error will result in the error message display since the position 6 is not in the range of the string error The remaining string functions do not have return codes INSTALLATION LIBRARY 4 33 LC LIBRARIES CONTROL FUNCTIONS o an am ee oe on The remaining functions included in the installation library not previously detailed perform miscellaneous tasks The syntax of these functions is as follows a aa wA au GAP A TU qu COUR iy es A e Gump 44m AAA uum W ee A ee dat e UD uum A Uer b Ee diam o COND xum COND We apap umm m
80. cp C cp cpzNULL return c The function getit inputs characters continually from the standard input until end of file or end of line characters are encountered When getit is called the pointer argument cp contains the address of a buffer area One by one the characters are placed in the buffer cp c and the buffer pointer is incremented cp Pointers may be declared for any data type An gian aS way of declaring a pointer is to leave out the size in an array declaration For example 3 LE int unii declares an integer pointer prime There is good reason for this method of declaring a pointer Pointers may be INDEXED to get to the nth item in an array Using the example above count would contain the address of the beginning of an array of short integers count denotes the first element in the arrays and count 22 J denotes the 23rd element E No matter how pointer is declared either method of using the pointer may be used as the programmer sees fit Thus count and count 9 refer to the same data item and may be used interchangeab ly in the same program Using count is a little more efficient however Pointers may point to other pointers This bombshell of a statement is probably too much for you after the last few paragraphs it must be said however LC allows pointers to have more than one LEVEL OF INDIRECTION This can be declared several ways shine
81. ct 7 The break statement is used to exit the switch statement switch month LR m case january case october case december case july case august case march case may days 31 break case september case april case june case november days 39 break case february if leap year days A else days 28 break 29 default days 8 error true STATEMENTS 2 26 LANGUAGE DEFINITION WHILE STATEMENT while expression statement The most basic form of looping is provided in LC by the while statement Simply stated while the expression results in a true non zero value statement also called substatement is executed The expression is evaluated before each time the substatement is executed Therefore the substatement may be executed from zero to any number of times depending on the expression If more than one simple statement must be placed in the loop substatement then the substatement must be a compound statement The break statement can be used to exit the loop from within the statement The continue statement can be used to continue directly on to evaluate the expression skipping the rest of the substatement from anywhere within the statement while driving watch the road while jogging take a step breathe if too tired break DO STATEMENT do statement while expression Do differs in only one way from the while
82. d stay away Ga this sort of MERE Y if you can UNSUPPORTED PRIMARY EXPRESSIONS The primary operators and gt which are used with structures and unions are not supported structures and unions are not supported either EXPRESSIONS 2 16 oem va em HN m M LANGUAGE DEFINITION UNARY OPERATORS t 4 3 9 31 435 31 5 41 31 2 721 5 2 3 2223522227232232 Unary operators operate on one object hence the name If more than one unary operator operates on the same object the operators are evaluated right to left The unary operators supplied by LC are OPERATOR OBJECT DESCRIPTION o wo mme expression indirection means object at amp Ivalue pointer means address of expression negates the expression l M minus expression expression logical complement E NP not expression T expression one s complement 3 of expression lvalue increment and save in lvalue e lvalue decrement and save in lvalue GER ay GUE AUD me ee de ow ARD GG ee ee O ae UA ee VEDO UD qup CH D VEDO VD ue H4 EDO VDO UA WP UND GU UMP UMS ce UA a es ee es ee fia man HERR A VEDO A Gane O A UA es Oe ee ma oe s Ge Aa pe dum cum d cum Se UR UN Ae dm Ah Heo TH undi NR bm qu mbe u dum e dm dum um e e d dm dm ee 3 m bm nd Anh m An es B O cd ms m THR m eee ee A B B B B B By All unary operators must appear before prefi
83. e HS Aum Ami e Cum MP Ame WP Ame e Cua A dE A LAS C ami Ke AA AP m mo W We ao m retcod atod str dvar ASCII to double retcod c atof str fvar ASCII to single retcod S dtoa dvar str double to ASCII intval dtoi fvar double to integer retcod dtof dvar fvar double to single retcod ftoa fvar str single to ASCII q ftod fvar dvar y single to double retcod itod ivar dvar integer to double retcod itof ivar fvar integer to single intval x ftoi fvar single to integer dvar specifies a double precision field fvar 3 specifies a single precision field intval specifies the integer value returned ivar specifies an integer value str specifies a character string field Wwe ap as de me ar 20 bar Di ao R P am A m dms O dms R P MD imas drat ua ID vum amm AA drat GER UMP R p d ha CUD CUD i u bat anm cum ub ut 6m dm cm ed cum TER AA c oe The above conversions should be self explanatory The conversions not shown above that convert ASCII to integer and vice versa are part of the ES library and are documented in a preceeding section of the LC R e pes l The C itoi function has not been imp lemented for obvious reasons FLOATING POINT LIBRARY 4 43 LC LIBRARIE Ss FLOATING POINT EXAMPLE ew AR um ow Re une Ge ub Ge ED e ip T oe oh Cum c ee nib ce d n The tia i
84. e of the remainder in the integer division of the two expressions The additive operators result in the addition or subtraction of the two expressions In subtraction unsigned subtraction only takes place when both expressions are unsigned If one of the expressions is a pointer and the other is not the other value is adjusted to reflect the size of the object pointed to Thus if p is a pointer p 3 returns the address of the fourth object pointed to by p If p points to integers then LC B automatically doubles the offset to account for the two byte elements The shift operators shift the left hand expression by the number of bits indicated in the right hand expression Zeroes are shifted in to replace the bits shifted out If the right hand expression is negative or zero no shifting takes place If the right hand expression is 16 or more the result is always zero Relational operators result in a true 1 or false value depending on the indicated condition The equality operators equal and not equal respectively also return true 1 or false depending on the two expressions equality K The bitwise AND operator does a bitwise AND with the two expressions Each bit position in the result will be set to be one if and only if both corresponding bits in the expressions are equal to one This is useful for isolating individual bits within a word by using a mask as one of the expressions Any bi
85. e parentheses separated by comma s LC is very liberal about the primary expression ANY valid primary expression can be invoked as a function regardless of the type of the primary expression Thus it is Perec acceptable to write 8x2262 to call the function at hex location 2969 This would call the PAUSE routine An the TRS 8g ROM Any number of arguments can be passed to the called function Care must be taken that the number of arguments passed is the number that the function expects Otherwise unpredictable behavior may result certainly not correct behavior If a variable number of parameters must be passed then a control indicator must be passed to tell the called function how many arguments there are for example the fprintf and printf functions in the standard library A11 arguments listed in a function invocation must appear on the same line in the LC source file This is not a limitation imposed by the C language but by the LC implementation Arguments can be any valid LC expression including other function calls The arguments are evaluated from right to left i e the right most expression is evaluated first The programmer shou ld not rely on this order of evaluation since some other implementations of the C language evaluate them left to rig ps Statements like this one funk argh V will cause different elements of arg2 to be passed to funk when different C compilers are use
86. ed for the propagation Note the difference between strept and fill INKEY The inkey function makes a single scan of the keyboard and returns the ASCII value of any depressed key It will return a zero if no key is pressed INPORT The funetion inporto returns as an integer the value read from the See Vinee port Rs INSTALLATION LIBRARY 4 34 LC LIBRARIES QUTPORT The Binet outputs the a value to the port The value is truncated to its low order byte CURPOS The current location of the cursor can be recovered with the curpos function It returns the cursor position as an encoded value The cursor row is in the high order byte while the cursor column Baa p the low order byte of the integer return code CURSOR To reposition the cursor use the cursor function The cursor is re positioned to the location identified by the arguments If the position that would result is not on the CRT screen a range error 1 is returned x must be in the range 8 63 while y must be in the range lt P 15 gt DATE The date function will place the system date into the string s The format is MM DD YY The string should be defined as a character array of minimum dimension 9 TIME The time function will place the system time into the string s The format is HH MM SS The string should be defined as a character array of minimum dimension 9 CMDI
87. ee WP Code M E CUR GF O a A A ae Cum Ou hs a a a oe uw WAP UP up uns p d dam VeRO de m GER tis Kum Us VO YS dih up Ps GARS URP UMP oes VEND Ue 4A 4A Vs Va O UMP UR ee uw CEP ee ee UND UND wu oe A uum eee ee d p A ap eum mr AED UNA ee ER oes oes Gp Ve Um ds V oes Putc is used to output single characters to a file c is any of the 256 possible character codes If an integer value is passed it is left truncated so that only the least significant byte is output RETURN CODE The return code cret is the character passed in c if no errors are detected otherwise it will be different from the character passed in c WARNINGS fp must be a valid file pointer obtained from fopen or one of the Standard I O pointers stdin stdout stderr or destruction of files may occur EXAMPLE if putc c fp c return 1 else return P STANDARD LIBRARY 4 17 LC LIBRARIES PUTCHAR S This function is used to write a character to standard output Its syntax is 3 qu qu up 9 me de Ue WAS dua Ap Gub CUP d dat Gu MVP oe 0 we we Wim GU dub GR CUP dub u Gm Wi GU My dinb dap C Yr e a we Qua di C on dee deo dub CUP uen a ee oe CP emm dim a on GUT e um dim dm c ee x e Por Hu Por dub qe ere aa FRA gap Uwe w GS ee tee Uum CHUA Ge PU dep A AM Mus CN we Cu ap aa UP apn uim Quum Ge O DAE W UD Wis eee eus ee ux A eee den eee Dem cum P em HD Dem ee we um uns e cret putchar c
88. ement The null statement is simply a statement terminator semicolon by itself with no preceding statement nu11 do nothing function a null statement EXPRESSION STATEMENT An LC expression followed by a semicolon is called an expression Statement The expression is performed when it is encountered LC will allow an expression that has no assignment in an expression statement even if it does nothing Expression statements are used to assign values to or modify values of variables or to invoke functions Some sample uses of expression statements TS function call a function retcode Cal a b c 6 nac a b c equal to counter pa increment a counter 1P STATEMENT if expression statement if expression statement else statement The if statement gives the programmer the capability to decide whether a Statement will be executed The criterion for the decision is the result of evaluating the expression The expression may be any valid LC expression If the expression evaluates to true non zero then the statement is executed If the expression evaluates to false zero then the statement following the else if any is executed If statements may be nested i e the statement within an if Statement may be another if statement Too much nesting of nf statements can be deii to follow so moderation is advised STATEMENTS 2 25 LANGUAGE DEFINITI
89. emory allocation functions and to provide basic operations that LC programs require such as MULTIPLY OR and AND The library is constructed as a Partitioned Data Set LC functions are stored in assembler source form as members of this data set The standard library is accessed by the EDAS assembler from the SEARCH LC LIB command Any member needed by your C language program is automatically linked with your program during the assembly phase of the LC compiled output See the chapter titled OPERATOR S GUIDE for more information CS STANDARD LIBRARY PM LC LIBRARIES ALLOC This function is used to allocate a memory block Its syntax is ptr alloc nbytes nbytes unsigned number of bytes needed ptr address of the block allocated Alloc is used to dynamically allocate memory during program execution The complementary function free is used to release memory allocated through alloc Alloc may be used to get table or buffer space when the amount of memory space available is unknown such as a program designed to run in any size memory machine 16k 32k 48k The programmer can call alloc with decreasing size of requested space until the Space is allocated RETURN CODE If a memory block has been allocated the value returned is the address of the memory block If insufficient memory is available to satisfy the allocation alloc will return a null 9 WARNINGS The program
90. ent followed it i 94 gt not a pointer expression the indirection operator HAH was used with an expression which does not result in the address of an object in memory LC ERROR MESSAGES 6 2 APPENDIX ERROR MESSAGES 95 gt not enough memory When LC began not enough memory was free for LC to execute pes Decrease the amount of modules in high memory filters MINIDOS KSM SYSRES ed overlays etc and try to execute LC again Ln 96 gt output file error An error occurred while writing to the output file 97 gt output file open error An error occurred when attempting to open the LC output file 98 split for The expressions in parentheses in a for statement must appear on the same line This is a limitation of the LC implementation not a limitation of the C language 99 split function call All the arguments in a function call must be given on the same line This is a limitation of the LC arene aeons not a limitation of the C language 199 too indirect The expression exceeded the amount of indirection allowed by the declaration of the objects used in the expression 1015 too m n y active loops LC allows nesting of loops and switch statements to 25 levels The loop or switch being processed would have nested more than 25 levels 192 too many arguments There were too many arguments specified in a function call LC limits the number of argument
91. ents on the Z 84 machine stack Each argument is pushed onto the stack as a two byte value Arguments are pushed in order opposite of the order they are specified in the function call Here is the assembly language which LC generates to perform a function call mE x func a b c LD HL C PUSH HL LD HL BS PUSH HL LD HL A PUSH HL CALL FUNC This process generates the following structure on tne 2 89 machine stack B E SP 6 gt lt c gt SP44 gt lt b gt SP 2 gt lt a gt SP gt return address That is how the arguments appear to the called function when first entered There are several methods which can be used within the called function to obtain the arguments The simplest method is to POP each argument off the stack This is not suitable for large numbers of arguments but most efficient for 3 operands or less Using the example above the arguments could be retrieved as follows FUNC POP AF return address saved POP BC sargument lt a in BC POP DE sargument lt b gt in DE ASN INTERFACING 3 ADVANCED TOPICS POP HL sargument c in HL PUSH HL srestore argument lt c gt PUSH DE 3 s lt b gt PUSH BC s J PUSH AF stack is same as at entry Note that the stack is returned to its original condition It is always important to keep track of the stack pointer However the contents of the stack i e the arguments are owned by the called func
92. eur JW lige Ww See deer iL R EV 6 D E N A B B E E dug Tide eid T a gi ama t er tma dtm Ea s ar fms Ut ae m PRAES He t ae S x a Pow US a E ee adeeb kw War E eria E LO lt HTH E TEH A E A ee T IND ON Meis s
93. f the installation library IN LIB or the floating point library FP LIB If your application will be using functions in either library you will need to add the nia foption FPLIB B foption INLIB for the floating point and installation libraries respectively LC has reserved additional option names for use with the T directive These are ARGS specifies that your program will will NOT be using command line arguments argc argv LC will suppress the run time code normally used to process arguments thus reducing the size of your CMD program FIXBUFS Specifies pre allocation of buffer space for standard 1 0 KBECHO Specifies eee of band input mE EE to the video display when inputting from a file opened with filespec KI MAXFILES specifies the maximum number of concurrently UR wx s4 opened files permitted REDIRECT specifies that your program wi1 Qi i1 NOT be using standard 1 0 redirection gt lt f LC wii suppress the run time code normally used to process I O redirection thus reducing the size of your CMD program For additional information on the use of these options and amp opt ion in general read the section on options in the ADVANCED TOPICS chapter LC OPERATION 3 5 THp remm O eee OPERATOR GUIDE fasm fendasm fasm transparent assembly language code fendasm The directive pair fasm fendasm can be used to insert assembly language sour
94. g is that there is no upper limit on the length of a string in the C language A string is stored contiguously in memory The last character of the string is denoted by a null byte hex zero at the end Thus any array used to store a string should be defined with a size one byte greater in length than the maximum length of the string it is to contain This will allow for the storage of the terminating zero byte For Ine pancen the string Hello is stored as shown in hex 4B 65 6C 6C 6F 99 The string functions provided in the installation library correlate with the string functions provided in various implementations of Microsoft BASIC Again remember that no ews string allocation compression takes place in these routines The string Wieden brear strcmp strcpy and strlen are documented in this section However since these functions are considered to be standard C functions the Lor are Supplied in the standard library eee INSTALLATION LIBRARY ee ae LC LIBRARIES The functions provided take the following format u u H li ii i u i li tt H it iu ti tt H il n tt i H H n n i it i t tt H it H ti it ti li n i U U L H H U H i H H n u strcat dest source retcod Strcmp string 1 string 2 strepy dest source v retcod strepl source dest pos count strept dest source repeat retcod strfind de
95. ich will return the status of the specified pixel The status will be zero for reset one 1 for set negative one 1 if xl yl is not in the CRT image or negative two 2 if the specified pixel does not contain a graphic character This integer value specifies the pixel position along the x axis horizontal or y axis vertical The value is a virtual pixel which means that p does not have to be a position in the CRT image However where a line being constructed only that part of the line actually in the CRT image ae will be plotted The direction away from the origin is always considered to be in the positive direction for more information on this subject see the pmode function RETURN CODE Return codes are provided by the above functions where applicable These codes are indicative of the following 0 Indicates that the pixel is reset point x y or pixel 2 x y J l Indicates that the pixel is set point x y or pixelte X y EN Indicates that the point Vic is out of range i e virtual and does not appear in the CRT image 2 Indicates that the pixel does not contain a graphic character point x y or pixel 2 x y 3 Indicates that the function code passed to pixel s invalid USE in the range lt 2 gt EXAMPLE This routine plots a horizontal line for x y 49 x lt 128 x set x y INSTALLATION LIBRARY 4 LC LIBRARIES C ADVANCED PLOT
96. ification as Follows DO LC FILE MYPROG 1 which looks for input and places output on drive one 1 The first stage of the LC language process is of course to create an LC source file The editor that is a part of EDAS IV is provided for this purpose In order to use EDAS for the creation and maintenance of LC source files execute EDAS with the command EDAS LC The EDAS manual should be consulted for al operations concerning the edi tor or assembler functions LC OPERATION 3 1 OPERATOR GUIDE The second stage of the LC process is the compilation of the LC source using the LC CMD compiler Use the JCL procedure shown above However if you want to take direct control of the operation you can execute LC directly LC ds executed when a command line beginning with LC is typed at the DOS ready prompt or encountered in a JCL file The format of the command line is free form simply a list of input file specifications and option switches The command syntax is as follows e M ap uh GED Ge END ENDO CUR ae W oe AA um we W oe ND uu UD ae ae ee um uum a AV uuum uum e USD an a a GE a gum UD ae ume CUERO AV auum OF CH on aE GF A A ar we OF cuim EA AVE cer cupa we AAA ay Uum um ME e ow en Gu ams URS URD qus hb W A qu O O SED G URD qum Q amp A Se ee oup quus AD amas AD GU UMD cup QUA GEL GEL Gub UND SP qas Cm uum UP Gh uum CUR x usn ems CH uuum ee UD USD CN qu eme ee c D a LC filespec filespec switch switch
97. ile A file may be the console keyboard the RS 232 interface or any input device or disk file Up to max bytes will be placed in the buffer Input is terminated when either an end of line gon rend of file is encountered or maximum buffer size is reached i bonds 3 c For cie with LDOS JCL files keyboard line input is performed using the GKEYIN system call Fgets recognizes the BREAK key as the end of file from the eem a ke S RETURN CODE The end of file indication eofind is the return code eofind is NULL zero if an end of file is encountered otherwise eofind is lt buf gt STANDARD LIBRARY 4 6 Fiber Sen LC LIBRARIES FOPEN This function is used to open a file device Its syntax is H U it H it ii it U U it it it i it it it H ii i U U ii ii ti U it it U U i i i it H EL ji i it ji H Ji ji 4 H ii H i tt tt i li ii i H H it H ii it ii i it fp fopen fspec mode fspec is the address of the file specification mode the address of the access mode identifier yn or Rn read nw or ny write a or A append a te Rr summ uhr CER UA uum UD dup PP P es GR ee dip AMD onp Rr ees dup epe es CNRC UNT dp dip UNO UR UR GEO QUR AK COO ANDR UEM QS sump CUR A e UNES QUUD pp Se QUU UNA QUUD Oe AND QUA QUA UND PU c V pn oe UA PU C Rn summ Rr CUm AUR e PU ue diar PEO un HPE es ee nga C PR A GUB cune Un UNS UPS sum dwr e Wp umm
98. included using the finclude statement The file extension of CSH is used for LC Standard Header files A program to be compiled and linked with LC should have the file STDIO CSH included to compile properly STDIO CSH also defines various system dependent parameters such as end of file eof and end of line eol lt stdout gt lt stdin gt and lt stderr gt are addresses in the stangard library which do not need to be def ed before use The following listing is representative of the STD10 CSH file cluded with the LC package ELSIE STANDARD 1 0 CONSTANTS La fdefine EOF define eof a B defin eol Ex ka define EOL 13 define FILE char define NULL QM define TRUE 1 fdefine FALSE define true 1 define false 9 fdefine OFF define ON 1 INTRODUCTION 1 8 LET S MEET ELSIE FUNCTION LIBRARIES Commonly used LC functions are collected into FUNCTION LIBRARIES The functions in a library can be used by the programmer without the need to rewrite or recompile the functions needed Once an LC program has been compiled it can then be linked during the assembly phase with the functions it requires Only those functions necessary for the execution of the program are linked to the compiled program Certain functions required by many programs are included in a special library called the STANDARD LIBRARY The standard library is the common denominator between
99. instructive guide into the writing of C language source programs Chapter two is a good definition of the C language as implemented in LC Although some may find that complete enough one reference text is available that must be added to your library The C Programming Language by Brian W Kernighan and Dennis M Ritchie is the bible of C and is MUST reading It is filled with numerous examples and illustrations of each C statement and also contains example upon example of useful functions If you are new to assembly language the preface contained in the EDAS reference manual should be consulted for additional information The advice is to peruse the contents of both this LC reference manual and the EDAS reference manual to familiarize yourself with its information and content If you have any questions concerning the LC development system feel free to call or write however since the results of a C program rely heavily on exact syntax if your question concerns any aspect of the C language it must be submitted in writing All transactions need to be identified with your registration number s so be prepared to provide both your LC and EDAS registration numbers It would also be helpful to make sure your questions are not answered in the manual Speaking of registrations MISOSYS would like to provide you with the best technical support possible To provide this support we need to know who our customers are So please fill out the registratio
100. ion fields and place the result in the first field specified in the argument list vl In the event of an error vl is unchanged and can be examined to determine the cause of the error Only SINGLE PRECISION variables can be handled properly by these functions Use the format conversion functions described later in this section to derive the proper precision RESULTS In all of these functions vl will contain the result of the calculation if no error is detected Any error such as overflow underflow etc will leave the vl argument unchanged The argument v2 is not altered in any way by the functions RETURN CODES Each function has a return code of zero 9 if no errors occurred during the operation otherwise it will return a LEVEL II BASIC error code The femp function returns 1 or l depending on whether vl is less than equal to or greater than v2 Typical error codes would be 2 Syntax error 5 Illegal function call log negative number 6 Overflow d l x pues Division by zero FLOATING POINT LIBRARY 4 41 LC LIBR A RIES DOUBLE PRECISION OPERATIONS amb APP dae VH APP Xu pe ue cem Gun Tan ane Gu OP qu ue uum AM GP que un due um by pie mae amo M c P n I H The following functions can be used to operate on double precision fields length 8 Their syntax is as follows ome cua 20 FUR gua CUR cua 100 ua que cu
101. is no return code STANDARD LIBRARY 4 3 LC LIBRARIES FCLOSE retcod fclose fp T fp the file pointer Fclose is used to close an open file and to free the file control area FCA for later use The lt fp gt passed to fclose must have been obtained from fopen In LC exit also closes files however the programmer should use fclose to ensure compatiblity and portability There is a limited number of files determined by the MAXFILES compiler option including standard files that may be open at one time Fclose is used to free FCAs so an unlimited number of files may be accessed one after the other RETURN CODE sa wm me up UP s SB UD UD UP a The retcod will be non zero if no error was detected in the eros operation If an error was detected then retcod will be zero 8 WARNINGS The value passed to fclose must be a valid file pointer If it is not bored erie things such as destroyed disk files reboots etc can result EXAMPLE if lastc xla putout Pxla fclose fpl fclose fp2 printf Files now closed exit STANDARD LIBRARY 4 5 LC LIBRARIES FGETS This function is used to get a buffered line from a file Its syntax is 4 eofind fgets buf max fp buf address of the buffer area max the maximum length of the input string fp the file pointer Fgets is used to obtain a buffered line from a f
102. itch of the EDAS lt A gt ssemble command The makes temporary labels unique within each module B ASM OUTPUT STRUCTURE 5 ADVANCED TOPICS RUN TIME SUBROUTINES re co e n o En RE QE IN QC FU PER em Ahh f UA UEM 600 GA ee PA m d SED GAAP dii Py cmn HUM FR A program by LC performs logical arithmetic and data manipulation operations through two registers the HL and DE register pairs HL is the primary register DE is the secondary register The stack is used extensively to store intermediate results as expressions are evaluated Certain operations are performed using subroutines in LC LIB These subroutines are zx 7 mE it 1 1 1 H L LL H u H H it H i H 1 i H H u U H H U H il i H i U U 1 i u i tt 4 n M H M i tt n 4 tt i U it tt i 11 1 H it SUBROUTINE OPERATION PERFORMED Toa cee MEME GINT get integer in memory at HL into HL PINT put integer in HL into memory at DE 0R bitwise OR of DE with HL XOR bitwise exclusive OR of DE with HL AND bitwise AND of DE with HL 7 EQ returns DE HL l o 8NE returns DE HL GT returns DE gt HL LT returns DE lt HL LE returns DE lt HL GE returns DE gt HL eUGE returns unsigned DE gt HL d ULT returns unsigned DE lt HL UGT returns unsigned DE gt HL E RULE returns
103. le precision fields and place the result in the first field specified in the argument list vl In the event of an error vl is unchanged and can be examined to determine the cause of the error Only DOUBLE PRECISION variables can be handled properly by these functions Use the format conversion functions described later in tnis section to derive the proper precision RESULTS In ali of these functions vl will contain the result of the calculation df no error is detected Any error such as overflow underflow etc will leave the vl argument unchanged The diana v2 is not altered in any way by the functions RETURN CODES Each function has a return code of zero if no errors occurred during the operation otherwise it will return a LEVEL II BASIC error code as described in the list under SINGLE PRECISION The dcmp function returns 1 V or 1 depending on whether vl is less than equal to or greater than v2 FLOATING POINT LIBRARY 4 42 LC LIBRARIES DATA CONVERSION FUNCTIONS The need will arise to convert between double precision single precision integer and ASCII string The following functions exist for this purpose a am iu PM diat A MPO cum wwe MAD Y MD ax dm Ms RU ub cum m MAP UA h EP sU VA us ua AG A Y dm CU Aw u Ub o KP Me cm ur A m 0e X CS AI O er m aum tmi es UA xu dus CA CU uie E dune GR te dem o u u dem CA AuA M P an AS Heb SER CE AR M R
104. llustrates how the floating point library can be used in an application The example is derived from K amp R page 8 fctab print Fahrenheit Celsius table for f B 12 32 312 include stdio csh Tt include standard header file foption fplib ME force search of FPLIB main A T A lower int lower upper step fahr char celsius 4 provide space for Float 7 mE a char fivedivnine 4 space to hold 5 9 9 9 mnn char temp 4 temporary work space char thirtytwo 4 space to hold 32 9 char ELE Str 8 space for ASCII result B lower limit of temperature table ui An upper 312 upper limit step 20 step size Note that the calculation 5 9 9 8 was removed from the body of the while loop to speed up calculations atof 5 9 fivedivnine BA float 5 atof 9 4 temp float 9 fdiv fivedivnine temp calc 5 9 9 9 wur float 32 9 m fahr lower initialize to starting value x while fahr lt upper fahr amp upper are integers Atof fahr celsius float fahr i fsub celsius thirtytwo fahr 32 9 fmul celsius fivedivnine 5 9 9 9 fahr 32 0 ay ftoa celsius celsius str result to ASCII printf X 6 3d 8 8s n fahr celsius str fahr step note the assignment operator 22m e gt FLOATING POINT LIBRARY
105. mdi n n puts Enter command gets buf cmdi buf CMDITEST CCC APPENDIX SAMPLE PROGRAMS Test of cmd include stdio csh option INLIB char buf 19g J main int re puts Test of cmd n n puts Hit break to exit back to DOS n 5 while TRUE puts Enter command if gets buf NULL exit rc cmd buf printf nReturn code is d n rc CMDTEST CCC Des gt e APPENDIX SAMPLE PROGRAMS compare ccc finclude stdio csh int line cl c2 FILE fpl fp main argc argv int argc argv if argc 3 m puts Format error compare filel file2Xn exit line 1 fpl getfile argv fp2 getfile rtargy while cl getc fp1 l EOF 8 c2 getc fp2 EOF if cl c2 printf Difference at line X 19dXn line exit NA else if cl eol 1ine if cl c2 puts The files are equal n else puts Tne files are not of equal lengthin getfile fname char fname char fp if fp fopen fnape Ra NULL printf Open error 20sXn fname exit else return fp COMPARE CCC se APPENDIX SAMPLE PROGRAMS decom ccc comment stripper program 89 14 82 removes all comments and multiple white spaces define eof 1 define eol 13 int col tab string comment int c main poh col tab comment
106. ment The format of a label is a valid identifier followed by a colon The following are labeled statements calculate i 10 bigblock i j k 1 m n 0 p 04 STATEMENTS 2 39 vtt nem nm ne nme nm emen aim OPERATOR GUIDE LC OPERATION de takes C source code as input and generates an EDAS Version IV compatible assembler source file as output Thus the output of the compilation process must be assembled and linked with any required run time library module before it can be executed The assembly and linking process is performed using the EDAS IV assembler A Job Control Language JCL file LC JCL is provided to present the compilation and subsequent assembly as a job stream to the operating system The JCL procedure requires minimal entry of commands by the programmer to create an executable CMD file The JCL file oS Batch creation of a runnable ELSIE program Format is do lc file lt progname gt show if show lc file 1 else lc ffile end ed jcl bci Ic lt cprogram file if show affilef we else affilef nl end Completed compilation If you want to compile a program called myprog and generate the finished CMD file with only one statement then the command DO LC FILE MYPROG See ATTENTION on page 3 11 lets you sit back and relax while the machine does all of the work If the ASM and CMD files do not already exist you may want to enter a drive spec
107. misspelling is accepted Certain switches have operands which are specified by following the option name with and the operand For instance output myfile 3 will cause the output by the compiler to be written to MYFILE ASM on drive 3 instead oe the filename that would have been the default COMMENT This switch controls whether the original LC source code will be written to the assembler output file as comments The normal default is ON The C source appearing as comments may be instrumental in your understanding the compiler output as it generates a minimally commented assembly source program GLOBAL controls the definition of external variables If the switch is turned off variables declared external are not defined in the assembler output If turned on external variables are defined in the assembly module output This switch defaults to on For more information on using the GLOBAL option see the ADVANCED TOPICS chapter LIST The standard output would normally receive minimal feedback during the compilation process If the LIST option is turned off LC will write each function name followed by a period representing each statement in the function An example of this is main o n move min max p A E aae v E vada au Ps No errors found If you want to see the source code as LC is compiling you must specify the 1 option since the default is LIST Note tha
108. n Gr cle cum com Gre CUP cy cun cum cun GND OR Gy Cm CUM a qup AD UM Dem qua S CHA CF CF GP U uA quim sun Ue 4e Oum UND gum CUM FUR gua C CHA a quin Gub cum 20 G4 uu Cu HP cua Ames uim san cu cum m amm sun OU CUm CUR gui CUM CUL sum cua UA CUA GU A URB Gu cue GU A Ju ew cme Gui GU A uum 20 FER CUP auum quim ASA CMM um NO Abu chim UND Gus uh cwm HB sue ua 0 Gum CUM amm Gem debe G4 um ee ee GU quim A CUR CUR Gum um retcod dsgn vl B retcod sgn vl vl amp v2 E are the address of double precision fields mE retcod dadd vl v2 vl vl v2 o retcod dsub vl v2 vl vl v2 l retcod dmul vl v2 vl yl v2 l PM l l retcod ddiv vl v2 vl vl v2 l o E m l retcod dabs vl v2 vl abs v2 Lo E o E a retcod dcmp vl v2 compare vto v2 NONE HE l retcod dfix vl v2 vl fix v2 retcod dint vl v2 vl int v2 ema PP an sun Ct s AP gu Uu PWP DA au es Cum ee sun PWP i ets ei es CHA eet qua CUR UMP Uem eet UUP gui CUM gue ee gua ee oe ee ec ee cee sum CUU uA UND soe es es UA ee Cub DUM sum VM cua W uem qum uh FF CUR gum A UA Cin A APP aoe Fe ae C m qium ee eet quin chia UMP uu quim chia UM dem a ee Gui CHER e uum E chin GEB eS en thia ee W uum UU eee ee c n REP Au CUA ee hein fp quin Ames eee Cen m m These functions perform calculations on two doub
109. n crash when the next alloc occurs STANDARD LIBRARY 204 9 Cai i rrt ene o Ao e d A E E C Y LC LIBRARIES GETC This function is used to fetch input a character from a file device its syntax is c getc fp fp is the file pointer amb on ap cu OF tp ow dup on COLL UE COM a W A Au W A E OF n A Qus A A oe us Cau YO uu Oui ug A ow Gub Oe A A W A A oe A Gub A ee GE E A Gus SW O A Gus CUR oe GER Au GP OF up a oe dup x diui fae GER dm AU Gee dats Hs ds Run W ee Da ARRA Gina ee Run G Cus eu GW deu ee dune apo ape dian oe OD oe Ge ee ee air ee ee ee dmm CUERO ee Ge ee eee ee ep Se So Uum oe cd ee ee ee efan Cd Uu uu Getc is used to input a single byte from a file fp must be obtained from fopen or be a standard file pointer Any of the 256 possible binary codes may be input using getc An end of file code EOF 1 is returned if end of file is encountered RETURN CODE The return code is the integer value of the character input from the file If an end or file is encountered then EOF 1 is returned WARNINGS The fp must be a valid file pointer or devastation may result You are warned T If c is to be stored before testing for end of file it must be stored inan Integer variable If not the end of file value will be truncated and will remain ian EXAMPLE filecopy fp copy a file to the standard output FILE fp int c while c getc
110. n form packaged with the diskette and return it to us promptly postal card postage is sufficient The registration number located on the diskette labels must be entered onto the registration card and should also be entered in the space provided below The registration number must be mentioned on all correspondance with us or when telephoning for service so don t lose it Registrations LC EDAS iii LET S MEET ELSIE Befcre diving into Elsie we suggest that you do the following at a minimum 1 gt Read the entire introduction to get an idea of what LC is ii about 2 Make backup copies of the distribution P Elsie is released on two distribution diskettes The diskette labeled LC contains the LC compiler and all support libraries The second diskette labeled EDAS contains the macro assembler and editor and various EDAS support utilities We suggest that you make one set of archival backups and store them away in a secure area safe from dust dirt magnetic fields etc Then make a work ing backup of the distribution diskettes The procedures for making backup copies can be located in the UTILITY section of your LDOS user manual under BACKUP For your information LC is distributed on data diskettes 3 Create an LDOS system diskette with a maximum of free space If you are going to BOOT from this diskette then you will need a configuration that includes the LDOS keyboard driver at the barest minimum Also
111. nsion is given for a source file the default extension CCC is assumed It is recommended that you establish your LC source files with this file extension for uniformity and standardization If you use EDAS LC for your LC source code maintenance the use of the CCC extension is automatic The output file specification defaults to the same name as the first input file specified LC will append the file extension ASM to this name The drive specifier if any of the first input filespec is used as the drive specifier of the output file The drive specifier should be given if the output file must be written to the same drive as the input file The LC OUTPUT option may be used to specify a different file name or change the destination drive number Assembler source code output may be suppressed by turning off the OUTPUT can be helpful for quickly checking LC OPERATION 3 2 OPERATOR GUIDE syntax without generating an Tr file i COMPILER SWITCH OPTIONS P Ot wm qo QD Uh un GG OD GR a A wee De Qm Gp Gb Ub a we Compiler option switches are turned on or off by a or respectively followed by the name of the switch For example list causes the LC source code to be presented to the standard output device during the compilation The compiler regards any command line argument not beginning with a plus or minus as an input file specification Only the first letter of the switch is examined so partial spelling or
112. nt library routine the address of the first character represented by the array name should be passed For example atof 3 1416 fpnum FLOATING POINT LIBRARY 4 37 LC LIBRARIES atod 3 1415926 dad converts the strings containing PI to single and double precision and places the results into memory at locations fpnum and dpnum respectively If you are writing an assembly routine that win interface to the FP LIB routines the assembler statement FPLIB DEFL d should appear in your code This statement forces a search of FP LIB in the LC ASN file bn We wish to acknowledge our indebtedness to Insiders Software Consultants Inc for their book THE R K ACCESSING THE TRS 8g ROM Volume 1 which provides vital information on interfacing to the ROM math routines Although the functions in FPLIB do not require any knowledge of how the BASIC ROM in the TRS 89 functions it can be helpful to have THE BOK for a reference to explain the details of floating point operation FLOATING POINT LIBRARY 8 LC LIBRARIES FPINIT This function is used to initialize interfacing to the ROM math routines and force a search um the diia point library during the assembly of LC ASM Its syntax is E fpinitQ there are no arguments This function is normally called automatically by an LC program which has any module specifying option FPLIB In cases where normal initialization has been bypassed a direct call
113. oking LC with the DO LC FILE MYPROG command and the CEDAS assembly aborts with a Job Control Language Job aborted message you most likely mistyped one or more identifiers variable names function names etc You can easily discover the error by TENONO the procedure with the command DO LC FILE MYPROS SHOW LC OPERATION 3 11 LC LIBRARIES STANDARD LIBRARY The standard library LC LIB is a collection of useful functions that allows the user to interface with the world external to the program without having to know the specifics of the particular environment that the program is running in Thus a program can be transported in source form to a different computer under a different operating system Only the standard library need change between systems The library is defined in a device independent way So that a program can use any device for input or output Since any file is defined as a sequence of bytes all devices can be interfaced to as files LDOS already provides this type of device independence thus the implementation of LC I O is totally compatible with normal LDOS files The standard library also provides functions to perform machine dependent operations such as memory allocation and Character Set operations Every program in executable form under LDOS requires a small run time module in order to open standard I O and provide 1 0 redirection initialize the 1 0 and m
114. on is provided in the return statement The return statement is not required to return from a function When no statements are left the bottom of the function body is reached the function automatically returns as if a return statement with no expression were encountered Return statements are needed when a value must be returned or when the return must take place before the end of the function square num square a number return num num getline buf char buf line input buffer check for a valid file pointer if file pointer NULL buf N9 put a null string in buf return back to caller E fgets buf bufsize file pointer l STATEMENTS 2 29 LANGUAGE DEFINITIOMN GOTO STATEMENT goto label The goto statement causes an unconditional branch to the statement identified by label The labeled statement must be contained in the current function It is illegal to attempt a goto to a statement in some other function An attempt to do so will result in an error during the assembly phase The following example illustrates the use of goto note it is strongly recommended that you avoid the use of the goto statement rest time int time if time gt 2309 goto sleep else return sleep for 2 9 LABELED STATEMENT label statement Any statement can be prefixed with a label This construction is usually used to target the argument of a goto state
115. on o Storage Classes Dou eue qu EE are RE E 69005320000 eo o o no EXDFPSSIONHS descarada dorado Unary Operators sssesssoesoososossoseoososocsass Binary Operators 60s vu Ed v or adeat S Va OE Statements oomooomporoconcrorcoroserconcnnnesosos BREAK T es v T EV PES T T s CONTINUE oo o er oosocosn oso seso e DO WHILE eesnevnerveans e eennesvesn 16ar n b0 b RETURN anat areas PE SWITCH CASE DEFAULT NER WHILE 59 easy ee ee eis ESO Ed ee eee as cie Puro GUIA E vv a AOE RTE AR PE do LU Operation 4229 ous ERA E ERE FUE RE aR de File Specifications diia eaa REA AA ERES I ERR V Compiler Switch Options eee GUAE Compiler Directives didas LC A Simple EXercise Sad A A RR E E EA ERA VUE Library E Standard Library LC LIB ere reer rrr dae NR Installation Library IN LIB buic E is Primitive Plotting Functions ooooomomooo Advanced Plotting Functions oooooooooomooo Plotting Control Functions oooomomooomosoo o String FUNCTIONS ERE EA ETRE TR de ed Second Edition 1982 t f 9 4 KA KA k A Q9 00 C5 PN L KA S LO 00 d CR U L i b PO De prse E E n ET Mm n3 COO 10 Y Uy Sl t t tai A Bake tle CQ p ked c LH L P3 pd HM BQ t INO Pd no 4 23 4 25 4 27 4 29 5 Controi Fun tions RAT SAO Floating Point Library FP LIB sccccceeeeceeeee ARG Oe ewer mee cen ERKE RRR K RRR KR
116. oper method and results in better structure in programs is to define variables as extern when referenced by all but one of the modules USING THE GLOBAL OPTION OF LC m e e AM shared global declarations should be placed in a separate file to be include d by all modules which use them Only one module can have Global specified when compiled all other modules must be compiled with Globals in the LC command line It is usually convenient to use Global when compiling the module containing main This method is not normally recommended It is only supplied as a convenience to those attempting to compile extremely large programs already written without using extern and static It is best to learn to structure your functions into units modules containing a set of related functions and their related internal and shared variables USING EXTERN AND STATIC When writing a large program it is best to try and logically structure your program into modules containing related functions with the data structures they use within the same module Any data structures or functions in a module which need not be accessed by any external function can be declared as static These static functions and variables will be unique in name when assembled and will not be accessible to other modules so there will be no conflicts in naming Those data structure
117. or Model III This is the file that is assembled Notice that the bulk of the resulting CMD program is assembled from files via the GET statement and SEARCH statements If you have not yet read chapter five of LC OPERATION 3 5 OPERATOR GUIDE the EDAS manual you may want to TM n turn to the sections on GET and SEARCH located within the fifth chapter If your compiled program file was named MYPROG ASM it is linked into LC ASM by changing the statement GET CPROGRAM to GET MYPROG This is done simply with the EDAS editor or is automatic when using the LC JCL Job Control Language hands off procedure l For a great deal of your programs the only LC runtime routines needed will be located in the LC LIB library Since all LC programs need some of the routines in LC LIB that library is ALWAYS searched during the assembly process The floating point library FF LIB will be automatically searched if your program requested the floating point library search via an option fplib compiler macro This is explained in more detail in the LC LIBRARIES chapter Many useful routines are stored in the installation library IN LIB This library is not normally searched in order to save you assembly time when you need not refer to the IN LIB routines However it is very easy to force an automatic search of the installation library All you need to do is specify an foption inlib compiler macro in your LC source p
118. ou Id normally SEPARATE COMPILATION ft b ADVANCED TOPICS CREATING USER LIBRARIES mIipmEuImmmmmmLImzzI2mEIEzIET We encourage LC users to create libraries of commonly used functions This increases your productivity since functions need not be rewritten for each program A library should contain functions which are self contained i e they do not require the calling function to know about the library module s internal structure and do not assume anything about data structures that the calling function declares In structured programming lingo library functions should be data coupled and functionally cohesive Also functions should be tested and be well debugged before being placed in a function library IN LINE LIBRARIES A TEE can be created by appending LC output assembly source files together The assembly of each function in the library can be controlled by the IFREF pseudo op available in EDAS When you reference a user library function in your program the subsequent assembly of the program will cause the IFREF to be true for that function Otherwise if you have not referenced called that function IFREF is false so the function is not assembled This method is simple and does not require the use of the PDS utility Its disadvantage is that the entire library must be read by EDAS even if some of the modules do not get assembled The SEARCH directive for searching PDS libraries in EDAS is much f
119. our program a special assembler file LC ASM has been provided A listing of the file follows to aid in WALA its functions sLC ASM 89 99 82 gt Kek e This module is assembled to create the run time CMD program file The line GET CPROGRAM fetches the file containing your main program compiled by LC Separately compiled C source modules can be fetched by adding additional GET statements If you have created a user library ies add additional SEARCH statements wo e We de wo We ws Be BF ws COM lt LC is copyrighted 0 1982 by Jim ii XII ORG 529H K esTART LD HL 4049H s PIU Model I HIGH CALL 9M0D13 Test for Model I III JR NZ 5 Go if Model I AD HL 4411H else use III s LD SP HL set stack area CALL eco0 sInitialize CALL MAIN sExecute user prog LD HL Set return code PUSH HL CALL EXIT Back to DOS STEMP DEFL g sInit relative storage GET LCMACS Get macros used by LC GET CPROGRAM sFetch user program IF o INLIB s True if foption inlib SEARCH IN LIB gt sInstallation lib ENDIF IF e FPLIB irue if foption fplib FPLIB DEFL FPLIB OR FPINIT Force GET of fpinit SEARCH FP LIB E E ENDIF SEARCH LC LIB o Standard lib always STORG EQU 3Set to lst storage byte PROGEND DEFL STORG STEMP Establish program end END START The LC ASM file pusvides a front end that makes your program usable on either a Model I
120. piler declaration foption FPLIB to your C language source program This establishes the protocol necessary to invoke an automatic search of the floating point library in the LC ASM file via the SEARCH FP LIB statement The floating point initialization function fpinit is normally called automatically by LC s initialization routines if foption FPLIB has been specified However if the user changes or substitutes different initialization code the user s program must call fpinit Numbers may be stored in two different formats single or double precision Throughout the library routines two consistent abbreviations are used f for floating point SINGLE precision and d for floating point DOUBLE Precision Functions beginning with or containing either of these abbreviations operate on the precision indicated Single precision numbers are stored in four bytes double precision numbers in eight bytes The programmer may declare either an integer array or a character array to allocate space for variables in their program Both of the statements char fpnum 4 int fpnum 2 declare a 4 byte single precision field Both of the statements char dpnum 8 int dpnum 43 declare an 8 byte double precision field Take care in how you pass the parameters required by each function THE ADDRESS OF THE FIELDS ARE PASSED Thus if the declarations char fpnum 4j dpnum B are used when calling a floating poi
121. ple of how the C language avoids the trap of non standard extensions being included within the language INTRODUCTION 1 9 LET S MEET ELSIE CLOSING COMMENTS me UN qe e qe e VADO e e GA amm e EP um A oe da AP po ow dump Or oe ue eo O GAS GER oe Au m LC encourages the use of structured programming methods Unless one uses the goto statement heavily LC practically demands a structured approach to program construction This is not to say that writing programs with LC will automatically make you a good structured programmer This is a skill that is developed by learning and applying the basics Some understanding of structured design concepts is necessary in order to effectively use LC Probably the first frustrating thing that novice LC programmers will encounter especially if their experience is limited to BASIC and assembly language is the discouragement of the use of goto Kernighan and Ritchie in THE C PROGRAMMING LANGUAGE state that the goto is never necessary and in practice it is almost always easy to write code without it The concept to understand is that the goto s are hidden within the program statements LC provides in a coherent understandable form the program constructs that you have been building out of goto s Last but not least several texts are available that should be part of your library The first THE C PROGRAMMING LANGUAGE by Brian W Kernighan and Dennis M Ritchie published by P
122. program is going to make use of any of the functions contained in the IN LIB library you will have to insert the compiler directive statement foption IN LIB in your C source program INSTALLATION LIBRARY S LC LIBRARIES p E PLOTTING FUNCTIONS The plotting functions support the block graphics mode available to the CRT screen The installation library plotting functions include functions to control individual pixels picture elements as well as to create various line constructions The primitive functions are used to turn on turn off or determine the status of any point pixel in the screen image The syntax of these functions is u H H H ii 4 U li I H ii i H H i ii H i ii 4 16 U H U li i u U H i u i i u il if i u U U i ii u H i ii H i it H U ii U if H i H i U it it retcod pixel funcod x y retcod point x y reset x y set x y funcod specifies whether the pixel is reset 0 set 1 or pointed 2 X specifies the horizontal coordinate y specifies the vertical coordinate amn qp UM Game fue uo um ww x que que mr que m aie au mr am AERA mr GR BW oe A USD Quse une a ee ee ee A A JUR VUA ee ee June O A GP ue Gne GARA P ua cuum CA AUS GARA nce GARA um um A A WM iis AA tee 4s ee CONDO cung CUP X ee AUS ee eee G ee ee A m ee D AUD ARP une VU ee A ee ee A ee W eee T GC A GU CPUS uu uci ue GERA
123. r hand a quotation from THE ELEMENTS OF PROGRAMMING STYLE by Kernighan and Plaugher is appropriate Everyone knows that debugging is twice as hard as writing a program in the first place So if you re as clever as you can be when you write it how will you ever debug it The word maintain could be substituted for debug in the quote above and it would still be valid You must be able to understand later what you wrote into your program If others are going to have to maintain your program the principle of KISS Keep It Simple Stupid should prevail This is not intended to discourage the use of complex expressions Just keep in mind that the more operators involved in an expression the more difficult it is to properly place parentheses and keep the precedence of operators There are two kinds of expressions in many computer languages logical expressions and arithmetic expressions Logical expressions are usually for comparing things and for making choices The result of a logical expression is either true or false Arithmetic expressions result in a number Usually an assignment to a variable is made to save the result of the arithmetic expression or it is passed as an argument In many language implementations only one type of expression may be used in certain contexts For instance the BASIC program statement 1909 A C lt B attempts to assign to A the result of the comparison C to B This is not EXPRESSIONS 2
124. ram is an hierarchical structure of functions with main at the top of the hierarchy The LDOS command line which invokes the LC program is passed to the function main using two parameters argc and argv One LC program can invoke another program by using the cmd function When the called program finishes a special function exit is used to return a value to the calling program Programs can call other programs passing any arguments using argc and argv In a way each program appears as a function to other LC programs and to LDOS ENVIRONMENT 2 1 LANGUAGE DEFINITION Please scrutinize the illustration of functions in the following example mE o main The main function execution begins here E ds say hello do work say goodbye exit 9 a normal exit no error code P sorry we can t goto any of the functions below say hello o ES puts Hiya l watcha toot K EOS say goodbye mE NE puts Bye y aliti putchar eol do work n while not atina time attach nut bolt pass_on widget ENVIRONMENT 22 LANGUAGE DEFINITION STATEMENTS SIMPLE amp COMPOUND To create an LC function you have to state the action to be taken using LC language STATEMENTS in the desired combination Certain special statements are built into the language to provide the necessary programming constructs sequence iteration selec
125. raro PEE retcod pmode quadrant oooooonoonommmorsorarrro 4 27 o retcod point ANT se weed aes 4 23 printf control ng alg oe mkssrdad ras prom 4 16 cret putc c fd A MODI EM AUOD 4 17 cret putchar ads rs LI retcod puts string oras nc 4 49 O 5p Rut es sss doc ptr sbrk nbytes olas aw ENS ERREDLARTES QE CUL 4 29 set X y y coc n n o o coro nn ee rorsncnarnno c so 4 23 cetr cat dest SOUNCE Jo adds 4 39 retcod strcmp source dest mem neve 4 39 SErcpyl dest source Di 429 ek cai AE CES TERT 4 31 retcod strepl source dest pos count 4 31 strept dest source repeat j E E 5 retcod strfind dest source pos ss saes aaeeea ss 4 32 stright dest source count sss sss ss sss aae ere rere 4 32 strleft dest source count sss s s sse saan aea Raa 4 32 retcod strlen SOUC JE usse dkbteVA REFS PS ME cor 4 32 retcod strmid dest source DOs count ST 4 32 time s 5 pean Na ode EE a ERAS e Es TER cs 4 35 c tolower char oomonmmmmmoso TT keresse oe 4 21 c toupper char wan eer rr re eel E ge int xtoi hexs ida EE E e s 4 93 LIBRARY FUNCTIONS B lt Haa A Sine Bt Se Fats otio ae silage TE r H GEZ EEE R E TE e APPENDIX ERROR MESSAGES LC ERROR MESSAGES 3 ft m mmm I bbs tradi series The object being declared
126. referenced but not as yet defined are read and assembled by EDAS For the rest of this discussion we shall assume the reader has a working knowledge of the PDS utility The PDS BUILD command is used to create and initialize a PDS library Once created modules cari be appended to the library using the PDS APPEND command The function name in a module is limited to eight characters with no underline allowed When the module contains only one function it is convenient to have the module name be the same as the function name In this case the command pds append myfunc asm my lib pds is sufficient to add the function myfunc to the library my lib Note that it is necessary to specify the password when issuing a command which writes to a PDS The SURE parameter tells PDS that the member is not an executable program When a dd contains more than one function it becomes necessary to use a PDS map file The entry point specified in the map file is not important The names of all the functions in the module which are to be accessible when searching must be placed on one line in the map file For example if a module file MYMOD ASM contains three functions funcl func2 and func3 then the map file MYMOD MAP would look like this mymod asm func f func2 9 func3 and the command to append the module to the library MY LIB pds a mymod my lib map PDS will assume that mymod has an extension of MAP The
127. regs 9 regs 5 respectively prior to calling the routine at location address The regs array will be stuffed with the register contents that existed upon return from the called routine The return code will be zero if the Z flag is set upon return from the called routine otherwise the return code is one 1 For more information on the use of call see the Lat on ADVANCED TOPICS FREEMEM Freemem returns the maximum amount of memory which can be obtained from alloc or sbrk E Pa x INSTALLATION LIBRARY 6 Mas param en cl mide eq AO ae serre K STL C wem N a as LC LIBRARIES LC FLOATING POINT LIBRARY mi mmIcmmmmetezmmmtI BIETIESSEE 17 LC does not have floating point arithmetic built into the compiler Thus floating point expressions are not allowed in the normal manner However this floating point function library allows the programmer to use the floating point routines built into the TRS BU BASIC ROM These functions provide access to single and double precision math all the trigonometric functions random number generation and conversion to and from ASCII strings Before any floating point math can be done the function fpinit must be called Fpinit initializes some data areas used by the TRS 89 ROM floating point routines and sets up linkages for error recovery The calling of fpinit and the automatic search of the floating point library is accomplished when you add the com
128. rentice Hall is the Bible of the C language and is a required part of your own library We will refer to this Sook throughout this manual by the abbreviation K amp R for Kernighan and itchie Two other books ELEMENTS OF PROGRAMMING STYLE and SOFTWARE TOOLS uy Brian W Kernighan and P J Plauger published by Addison Wesley sresent a good foundation of structured programming concepts Prentice Hall also publishes THE C PUZZLE BOOK by lan R Feuer This book can be used to test your understanding of the C la age It has proven itself to be quite useful in testing out the intricaci of the LC compiler INTRODUCT ON 1 14 LANGUAGE DEFINITION PROGRAM ENVIRONMENT Functions Tp was cus USD was UN UA qua He e QUE UH Ge e ee e 4s OR Gs ume due d n Nub AV GE A 4mm Gas AE Gub UD que ur n cmm D Nn cm mime mm me m n T en Ma frs Un MN ves nn E map HEP ED um UP m e The C language is in a word functional The basic unit of program construction when using LC is the function Every LC program is a collection of functions Each function is a collection of statements that work together to achieve hopefully a useful well defined purpose Each function can have information passed to it when it is invoked called The elements of information passed to the called function are denoted as arguments In LC arguments are copied onto the stack The function can then access and use the local known only to the called function
129. rogram similar to foption fplib For eee 5 include stdio csh i foption inlib This statement invokes SEARCH IN LIB main int dot A for aed dot 128 dote set dot exit will schedule the compilation and assembly of your program with a forced search of the installation library to resolve linkage to the set function LC OPERATION 3 6 OPERATOR GUIDE COMPILER DIRECTIVES The LC compiler supports a handful of directives that control various aspects of the compiler during the compilation process One of these directives finclude filespec you will quickly become familiar with Others may be used less frequently They nevertheless provide additional power in the use of the LC E These directives are include finclude lt filespec gt This directive tells LC to insert the file designated by filespec into the source stream being compiled The lt filespec gt will default to an extension of CCC if no extension is given The include is used quite frequently to merge the STDIO CSH standard header file into your compilation An Miustration of its use is JX sample program to illustrate include include stdio csh main int x x 3 4 5 Bs printf d n x define fdef ine lt macname gt definition The define directive is a macro definition It creates a macro called macname which is defined to be the string of
130. rpreted first The three primary operators supplied by LC are isolating parentheses SUB SCRIP RING and Function invocation Oe expression isolating parentheses primary expression expression subscripting primary coii expression list function invocation KI sunm PARENTHESES When the order in which an expression is to be GZ conflicts with the DIE of operators the isolating parentheses provide a way around the conflict The expression within parentheses is evaluated first before the result of the enclosed expression is used in any expression outside the parentheses For example when predicting the percentage of up time for any ee ES following formula is used eniti eee EE CE uice MTBF MTTR MTBF mean time between failures MTTR mean time to repair When writing this formula into aC expression a conflict occurs because the EXPRESSIONS 2 14 E LANGUAGE DEFINITION division operator takes precedence over the addition operator If the expression is written like this up time mtbf mtbf mttr the result will always be mttr plus one This is because the division is done before the addition To avoid this the expression can be stated as follows up time mtbf mtbf mttr to achieve the correct result Parentheses can be used on either side of en aane operator At the risk of confusing the reader with as yet undefined operators we nevertheless provide an
131. rtable language the interface within a program to the external world is isolated in a standard library A program written inC using only the standard functions to perform input output and memory allocati n can be transported in source code form to another sytem recompiled and run with minimal changes The LC system includes a standard library which is compatible with programs developed under UNIX Thus programs developed under LDOS with LC will run under UNIX as well The reverse is also true except in cases where features not implemented in LC are used in the program developed under UNIX LDOS runs on a variety of machines with many varied configurations of 1 0 devices Any program written for one particular environment running LDOS can run on any other provided that the standard library is utilized The programmer should bear this in mind when writing programs to avoid conversions when migration to a new system becomes necessary INTRODUCTION 1 5 LET S MEET ELSIE STANDARD INPUT OUTPUT LIEZESECSTDICIZE ASI CES Any program generated by LC will normally have three files automatically opened when the program begins execution These files are standard input stdin normally the console keyboard standard output stdout normally the console display and standard error stderr normally the console display The program can access these files without opening them by using standard library functions since the LC stand
132. rtain types of programs such as screen and graphics editors the programmer may choose to disable the echoing of characters typed at the keyboard However for most programs it is desirable to be able to see what is being typed even if standard output has been redirected This option allows this flexibility When ON KBECHO will cause the getc function to echo all characters input from the keyboard to the video This holds Hue for ANY file opened as KI not e the standard input KBECHO defaults to ON MAXFILES This option m a numeric argument instead of OFF or ON as it is not a switch The number will be used to set up control storage for user Sto due The maximum number of files which can be opened at the same time is controlled by MAXFILES The standard I O files are not counted in this number For example if no user files were needed then MAXFILES could be set to zero MAXFILES also controls the number of buffers pre allocated when the FIXBUFS option is ON Thus it is best to use MAXFILES when FIXBUFS is E a ecu to minimize the memory pre allocated ror file buffers MAXFILES defaults to allow the user eight 8 concurrently opened files REDIRECT The REDIRECT switch controli the 1 0 redirection feature of the died library When REDIRECT is ON standard files can be redirected by command line specification When OFF no redirection processing takes place and the standard 1 0 files are set
133. s and functions declared in the module which need to be accessed by functions in other modules should be declared without any storage class This causes these functions and data structures to become external meaning that they are defined in this module and can be accessed from other modules When using a function or data structure declared in another module the extern statement is used to declare the type of the object extern is required for accessing variables outside the module However a function may be used without an extern the compiler will assume that the function returns an integer value If any other result is returned the function must be declared extern SEPARATE COMPILATION 5 3 ADVANCED TOPICS ASSEMBLING SEPARATELY COMPILED MODULES C am m o a P 4 AD o e P p eo 4e PA am UP P e HP e HD Moe oS UP s 0 m me n Each elude must be read and assembled by EDAS in the same assembly The GET assembler directive is used for this purpose A file should be created with GET statements for all modules to be included in a program This file name is then specified as the program name when assembling when using LC ASM SERE is an example of the GET file listing of MYPROG ASM GET MYMAIN GET MYFUNCS GET MORECODE When assembling load LC ASM into EDAS and then issue the following lt C gt hange command E C CPROGRAM MYPROG to set up the GET filename Then assemble as you w
134. s contained in this module These functions supply graphics plotting string manipulation certain LDOS entry points and other TRS 89 features INTRODUCTION l 3 E n uu n E LET S MEET E L S I E l i ome 2 pu The standard ETT header file supplies constants Lor eta which reas to use the standard A Mbrary CLCALIB re ne ar v This file Je e ad id source file assembled by EDAS It pu nh your main program and establishes the neccessary interfacing i005 between your program and the LC runtime modules needed to make a complete n uw ees e a IRE Mr III Po This CES contains othe tela defaults aid in language macros Pu referred to by the compiler and used by the assembler This file is M jui utet ra accessed byt EDAS when oo the LEASH file es 2 This file ds a Video filter f for the Model machine It E provides a more cup reasonable and less EUM dismay of the characters L M Doa ee INTRODUCTION 144 Ji is Am LET S MEET ELSIE LC ENVIRONMENT SER ee NUR ee FUR GM GER GUN GP d P m EB HA SPPP dum SPPP SPP ee naga UU EP NUM NU A LC was designed to be compatible with C programs written and intended to run under UNIX Thus some features of UNIX were incorporated into the design These features include standard I O devices standard 1 0 redirection device independence command line arguments and dynamic memory allocation To make C a po
135. s in LC are evaluated using 16 bit arithmetic the expression is negated for the full 16 bits The unary logical complement operator or not operator evaluates to false if the expression is true and to true if the expression is false False is defined as and any non zero value is considered to be true However al LC operators which result in true or false use one 1 as the value for true Thus the least UL bit of the result indicates true or false The one s Gump denen operator inverts every bit in the expression No regard is given to the type of the expression The increment and decrement operators may be used either before prefix the operand or after postfix the operand The operand must be an lvalue or lvalue expression In either case the contents of the lvalue is incremented or decremented and stored back into the lvalue The difference between prefix and postfix is whether the result of the expression is incremented or not Prefix means that the value after the increment or decrement is the result of the expression Postfix means that the value returned by the expression is the value before the increment or decrement UNSUPPORTED UNARY OPERATORS ape JP a Au dum emm uum deje EA Gus a um ee E um A y i dup GARA TEA a di de JU e type neme and sizeof operators are not implemented in LC UNARY OPERATORS 2 18 M re H O aere E LANGUAGE DEFINITION BINARY OPERATORS R R L
136. s in a function call to 16 This is a limitation of the LC iia ON not a limitation of the C EE 183 unmatched arguments The argument being declared did not match any of those in the argument list for the function 194 unrecognizable declaration The object being declared contains a character which is invalid in the context of a declaration 195 unrecognizable option One of the options specified in the command line was not a valid LC option LC ERROR MESSAGES C 3 T l A c y i MEEUERSEE TT PROGRAMS CAT CCC Utility to concatenate files to standard output adapted from The C Programming Language by Kernighan and Ritchie include stdio csh FILE fp main argc argv int argc argv if argc 1 no args copy standard input filecopy stdin else while argc if fp fopen argv r NULL fputs argv abort open error y else filecopy fp fclose fp filecopy fp copy a file to the standard output FILE fp L int c while c getc fp EOF if c putc c stdout abort Output file write error abort msg char msg fputs msg stderr putc eol stderr exit 1 let system know about the error Bu CAT CCC D 1 APPENDIX SAMPLE PROGRAMS Test of cmdi include stdio csh option INLIB char buf 199 main i puts Test of c
137. sion when the context of the program required an expression 75 invalid option name The name given in a option compiler directive was not a valid LC identifier 76 invalid option value The value given in the option compiler directive was not a character literal or numeric constant 77 local symbol table overflow LC ran out of local symbol table space Either decrease the amount of memory reserved in high memory see not enough memory error or decrease the number of local variables in the function 78 gt line too long The input line exceeded the maximum input Tine size allowed by LC 128 characters line l LC ERROR MESSAGES APPENDIX ERRO R MESSAGES 79 macro table full The current define caused the table space phage bag by LC to be exceeded Either decrease the amount of memory reserved high memory see not enough memory error or decrease the number of def ine statements in the module 89 missing ua operator was found without a matching operator mE o 81 missing apostrophe A character literal was not ended with an apostrophe LC does not allow a character literal to be continued on enotne line 82 missing bracket The ending bracket character shown in the error message was expected but was not found 83 missing quote A string literal did not have an ending quote Strings cannot be continued on another line 84 gt
138. ssion 2 d is evaluated like this expression expression L expression 1 lt op gt expression e The first form is more efficient since expression l only need be evaluated once BINARY OPERATORS 2 23 LANGUAGE DEFINITION LC STATEMENTS REE S S LC statements are used to specify the action to be taken by the program The statements given in the program are executed one after the other Certain Statements conditional and looping statements will direct the order of and conditions for execution of other statements Some definitions of statements in the following text require that a substatement be included in the statement Any place where a substatement is required there may be one simple statement or more than one statement combined in a compound statement SIMPLE STATEMENTS Simple statements are of three types expression declarative and control The declarative statements are described fully in the previous sections on functions and variables The type size and scope of functions and variables are declared in declarative statements l A simple statement always ends with a semicolon The semicolon is the STATEMENT TERMINATOR It is not a statement separator as in the PASCAL language It is always required at the end of a simple statement COMPOUND STATEMENTS The left and right brace characters and are used to indicate the beginning and end respectively of a compound statement A compound statement
139. st source pos stright dest source count strleft dest source count I retcod strlen source retcod strmid dest source pos count cout is the integer sub string length dest is a pointer to the destination string pos Starting nde position or array subscript source bs a pointer to the source string repeat a repetition counter Plies Ases pp ee ee aio Ee eR Paes MEER T ee Ce dung a ee AERA A TE mu RD eae A Hak A GERA I ek GR mmm R x mp ED amp CAD am an ap svib UD aes dW GE ap at n e GUB ans Ll ee bat y GEM 2 Gm UD m ana i Ca euge n e hie ee ARR ro by W mB B et ARA M bie eee GERD CUR UM GENE GEM CUR YB UEM ba ee ARR a a A m GENER s ums A mo A CU GE GEM Pe CU e re HE d ee E a ms PS ES ee Gu ee E a W NEP a eee ee ee ee GEM EH ee The strcat function will concatenate append the source string to the destination string STRCMP The function strcmp will compare string 1 to string 2 If the string 1 would appear above string 2 in an ascending sorted list the return code will be negative lt P If the two strings are equal a zero will be returned A return code of a positive value greater than zero gt indicates string 1 to be below string 2 in an ordered list If you are unfamiliar with how ASCII strings are ordered perhaps a strong example will clarify this discussion The following is an ordered list of strings in ascending order
140. statement the expression is evaluated after the statement is executed Therefore the substatement will always be executed at least once The substatement will be repeatedly executed until the expression evaluates to false non zero do anything while there_ is still _time ya shuffle routine do cut the cards shuffle while ready to deal STATEMENTS 2 27 LANGUAGE DEFINITION FOR STATEMENT for expr_l 3 expr 2 expr 3 statement The for statement is a looping statement which provides a convenient place for initializing testing and incrementing Toop control variables The format shown above can be rewritten using the while statement expr 1 while E expr 2 statement expr 3 fie 1 is evaluated once before the loop is entered The test expression expr 2 is evaluated before each execution of the substatement If it results in a false zero value the loop is not executed and execution continues to the next statement Expr 3 is evaluated after each time the substatement is executed B Both expr 1 and expr 3 can be more than one expression separated by commas Expr 2 can only be one expression and should result in a logical value Due to limitations of the LC implementation all three expressions in parentheses must be on the same line for cs A 5 c lt Z tc putchar c print the letter Now I ve said my ABC s BREAK STATEM
141. t in the mask which is set to zero will cause that bit in the result to be zero Any bit set to one will cause the bit in the other expression to remain the same BINARY OPERATORS Don LANGUAGE DEFINITION The bitwise exclusive OR operator Each bit in the result of an exclusive OR is set only if the corresponding bits in the expressions are opposite i e 1 and or and 1 If they are the same that bit in the result will be zero This can be used to complement bits using a mask expression Any bit which is 1 in the mask will cause the corresponding bit of the other expression to be complemented in the result Any mask bit which is 9 will pass the corresponding bit unchanged into the result The bitwise inclusive OR operator Each bit in the result will be set to 1 if either of the corresponding bits in the expressions are equal to 1 This can be used to set any particular bit in an expression to one by using a mask expression If a bit in the mask is equal to 1 then the corresponding bit in the result will be set to 1 If abit in the mask is equal to then that bit in the result will be the same as in the expression being manipulated i LL Wb due 4 VU The logical AND operator results in a true one or false zero condition depending on the relationship of the two expressions The result is true only if both expressions are true non zero Moreover if the first expression is false the second is never evalua
142. t since listing output is to standard output it is subject to I O redirection Thus if you want a printer listing for Nhasever reason you could specify PR in the LC command line LC OPERATION 3 3 OPERATOR GUIDE OUTPUT SPEC This switch controls the output of the compiler to the output file If the switch is off no output file is generated However if it is on but no SPEC is given LC appends ASM to the name of the first input file in order to create the output file specification When a file specification is given for SPEC it becomes the name given to the output file A default extension of ASM is inserted if no extension is given If only a drive specification D is given the output file is written to that drive with the same file name as the first input file This switch defaults to on with no SPEC When this switch is on the compiler will stop when any errors are found and displayed Any key except BREAK will continue compilation BREAK will abort the execution of the compiler at any time if this switch is on If LC was invoked from JCL the JCL will also be aborted This switch defaults to LC OPERATION 3 4 OPERATOR GUIDE CREATING A CMD D Once the LC compiler has compiled your program into assembly language you need to use the EDAS assembler to create the CMD file In order to provide the proper initialization in the CMD file and ensure that all necessary runtime routines are linked with y
143. te compilation is not being used you have defined two external objects in your program with the same name It is useful to familiarize yourself with the previous section on LC assembly language output structure Also if you are assembling separately compiled or user library functions a good understanding of the extern Statement and external versus static variables is essential Refer to the section on storage classes in Chapter 2 LC Language Definition t WHEN THINGS GO WRONG 5 17 eran c APPENDIX OPERATORS UNARY OPERATORS indirection object at oooooooooo o o T 2 17 pointer address Of disnea 2 18 negation ads n ee Serer 2 18 logical NOT esses TEPC Cee eT ee Tee E ee 2 18 one s complement APP E T 2 18 increment DR e Mis decrement cnn 2 18 BINARY OPERATORS VA multiplication eee eee TA WA WARS 2 21 GIVI STON 69 1x3 aac Yves dedos ini 2 21 modulus remainder sss sss s s s s s se P P 2 21 Addition i desea sess ids Sd d qued ur ated iUe uel subtraction Vedere Aio T aa 2 21 Shift AA L R EN N 2 21 shift right ansias an Lali TOSS Than coo sect suena avs e s Cael greater than PTT ys 2 21 less than or equal to cce nnn PE Aus 2 21 greater than or equal LO sese 2e ERR ORE E RE 2 2 equal 2 2 599 b ERAS
144. ted The logical OR operator returns a true 1 result if either of the expressions is true non zero If the first expression is true the second expression is not evaluated The conditional operator gives the C expression repertoire the equivalent of an if then else construct It can technically be classified as a binary operator since only one of the last two expressions is evaluated The first expression is evaluated as true non zero or false zero Then if the first expression was true non zero the second expression is evaluated as the result of the expression Otherwise if the first expression was false zero the third expression is evaluated for the result The conditional operator groups right to left a b c d7e f g is evaluated in the following manner a b c d 2e f g BINARY OPERATORS ATUM LANGUAGE DEFINITIO y Either or both of the second and third expressions can contain conditional expressions POP al QR el Ihe Ten IM The assignment operators place the result of the right hand expression into the object denoted by the left hand expression after performing the indicated operation with the contents of the Ivalue when an assignment operator other than is used The simple assignment places the result of the right hand expression unchanged into the object denoted by the Terem Nang expression The compound assignment operators have the form z expression lt op gt expre
145. tern so that it may be accessed within the currently defined function Local variables may not be accessed from any other functions They only exist for the function in which they are declared Even within the function a local variable can only be accessed in the block in which it is declared Remember a block is a Section of code contained within a matching pair of braces Local variables can have the same name as external variables or local variables declared in different blocks If a local variable has the same name as an external variable then the local variable is the one accessed when used within the local block In the following example int same funk same return same return local copy hunk Tn if block 1 int Same some code could go here E else char same some other code here ro X HE every declaration of same was a unique variable Although legal the declaration of local variables with the same name within the same function is not recommended This type of trickery as shown in hunk needlessly causes confusion and is easily avoided SCOPE 2 9 LANGUAGE DEFINITION STORAGE CLASSES o P R ap GE ul TP am mee am a am a Variables and functions may be declared as being in certain classes These classes specify where variables are to be stored The classes available in LC are auto static extern and register The storage class of an o
146. that other modules cannot get to these types of variables since the d is substituted at assembly time Labels which ASM INTERFACING 5 14 dm d o ine 7 AD v d CED TOPI UNS must be accessed by other assembly language modules should be defined without the in the label i e to keep them global If a variable must be accessed by an LC module which is to be defined by the assembly module then the macros described earlier in this section must be used to declare the variable and to access it within the assembly language module Examine the macros in LCMACS ASM to see how they work for additional v ideas RETURNING A VALUE Pa aS SS SS ee Se oe ee a ee e ee sss oo LC programs use the HL register pair for a 16 bit accumulator Any value to be returned by a called function must be placed in HL before returning to the calling function Take care that a full 16 bit value is returned If a character or 8 bit value is being returned then H should be loaded with zero If a true or false indication is to be returned HL Should be set to 1 or accordingly CALLING MACHINE LANGUAGE ROUTINES TE EINEN TER o ee UD E E PU A AAA AS O A E e FU A ie Gun da Beb e ee ee ly y Y E A E A A dum The call function has been provided in the installation library to standardize the invocation of machine language routines The use of call is documen ted on page 4 36 and illustrated in the program syscall which
147. tion You may be surprised at first by the limited number of statements built into the C language The authors of the language wished to maintain the generality of the programming statements forcing any special features to be outside of the programming language itself Other languages often have extensions in the form of statements to provide specialized features leading to incompatible versions of the same language BASIC is a well known example of a language extended in far too many different ways The C language avoids this situation by only providing those statements necessary for structuring the program s logical flow and by placing all special features into function LIBRARIES Function libraries are nothing more than collections of commonly used functions See the section on the LC libraries in the INTRODUCTION for more information Simple LC statements always end with a semicolon ms the STATEMENT TERMINATOR The LC compiler depends on the semicolon to tell when a simple Statement ends Any number of simple statements may be entered one after the other to form a SEQUENCE of statements that are executed one at a time first to last The brace characters and are used to enclose a sequence of statements to form a COMPOUND statement A compound statement can be used anywhere a simple statement can be used Thus the body of a function that portion enclosed in braces is just a special form of compound statement For ex
148. tion and can be used like any local variable A better method to use when neering with large numbers of arguments is shown below LD HL offset to lt a gt ADD HL SP sHL address of lt a gt VALE GINT get contents of lt a gt GINT is a run time library function which gets the integer pointed to by HL into HL See the Peer section on LC assembly output structure for more information Another method is to utilize the Z 84 index registers The stack pointer must be placed into the index register first then index offset values can be E used to get and store the arguments LDO IX 9 2 ADD IXSP sget SP into IX LD La 1X 2 get LSbyte of a LD H 1X 3 get MSbyte of a If an argument is intended to be a character variable only the least significant byte LSbyte is needed so a single indexed load is used LABELS AND CONSTANTS It is ie trans Ganie that the assembly language programmer utilize the EDAS MOD directive to assure that labels do not duplicate those in other modules The following method will assure that you will not have this problem 5 top dw a MOD VARi DM 8 EQU20 EQU 2 FUNC your function here IR FUNC2 go to temporary label FUNC26 ae o temporary label By appending the C7 your label becomes unique from all others in an assembly assuming that you placed a MOD directive at the beginning of the module Keep in mind however
149. tion on assembly language programming in the Elsie environment LC OPERATION 3 9 OPERATOR GUIDE A SIMPLE EXERCISE 7 7 ES emm A um db ee ee AP KU APR dup a om da not It may prove helpful to you to see a program generated from start to finish It will bea small one but nevertheless one that will exercise all of the steps needed to accomplish the creation of a CMD file If you have ever entered and or edited a BASIC program you are ready to perform this exercise Before we begin remember that you will need the LDOS keyboard driver activated A few of the extra keyboard characters will be needed It s probably a good idea to refresh your memory as to the key EOS ORE Character key combination S O CLEAR COMMA CLEAR SLASH CL EAR PERIOD E CLEAR SEMICOLON T CLEAR ENTER X CLEAR SHIFT COMMA CLEAR SHIFT SLASH CLEAR SHIFT PERIOD i CLEAR SHIFT SEMICOLON You must have the book The C Programming Language by Kernighan and Ritchie Open it to page 15 and note the program shown at the top of the page You are going to enter it First execute EDAS with EDAS LC The LCS parameter tells EDAS to accept lower case input set tab characters at every four positions and use CCC as the default file extension You will Observe the EDAS heading message Now enter the command i EDAS will go into insert mode and display the first Tine number As you enter each line terminate it with ENTER
150. to right or right to left If the order of evaluation between like operators does not matter the operator is said to be associative Here is an example of how the order of evaluation affects an expression a b c d This expression is evaluated a follows a b fc 4 Thus the division operator is said to group left to right BINARY OPERATORS 2 19 LANGUAGE DEFINITION PRECEDENCE OF BINARY OPERATORS Highest to lowest mp mp um e aa um To mp y o 9 p Hp 4 mm de M o m we Sum y 6m 6 um m UB D m m ma MULTIPLICATIVE OPERATORS group left to right expression expression multiplication expression expression division expression expression modulus remainder ADDITIVE OPERATORS group left to right expression expression addition expression expression subtraction SHIFT OPERATORS group left to right expression lt lt expression shift left expression gt gt expression shift right RELATIONAL OPERATORS group left to right expression lt expression less than expression gt expression greater than expression lt expression less than or equal to expression gt expression greater than or equal to EQUALITY OPERATORS group left to right expression expression expression expression BITWISE AND OPERATOR equal to not equal to associative expression amp expression bitwise and BITWISE EXCLUSIVE OR OPERATOR associative expression expression bitwise
151. tring operation will be aborted Bear in mind that this function behaves differently than the Microsoft BASIC MID function however the LC strepl function performs as a string replacement algorithm should perform STREPT The strept function replicates the source string into the destination string the number of times indicated by count Note that the replication uses the entire source SEDIT and not just the first gunudi Thus a statement such as strept newstring 19 INSTALLATION LIBRARY 4 3 LC LIBRARIES will create newstring equal to STRFIND The function strfind will search the destination string for the first appearance of the source string The destination string will be searched starting at the position dest pos If the source string is a null string the value of pos will be returned If the destination string is a null string a negative one 1 will be returned If the source string is found in the destination string its position relative to the beginning of the source string will be returned If the source string is not found i e is not a sub string of the destination a negative one 1 will be returned d STRIGHT The stright function will copy the rightmost count characters of the source string the sub string to the destination string This is NOT an append operation The destination string is replaced with the sub string If count
152. ur programs using LC ASM and GET your compiled C modules Your safest bet is to use LC JCL when compiling and assembling If you have written portions of your program in assembly language you may have a few more errors to deal with Please read the previous section on assembly language interfacing for hints in debugging your assembly language If you are creating a CMD file directly from the LC JCL file you will be aware of an assembly error if the JCL aborts from EDAS To specifically isolate the assembly error you will need to execute EDAS load the LC ASM file globally change CPROGRAM to the name of your C comp i led output program then assemble with the WE switch One of the following errors should prevail UNDEFINED SYMBOL A which you referenced in your program was undefined in any module in your program This can be caused by omitting the definition misspelling the identifier or defining them incorrectly A look at the name which is undefined will give you a clue as to which situation was the cause Misspelling should be obvious Look out for upper case versus Tower Case names Remember that LC is case sensitive MULTIPLE DEFINITION A symbol was defined twice with the same name If you are assembling separately compiled or user library functions you may have named two external variables or functions the same To correct this make one or both of the identifiers static within the module If separa
153. vr 4 42 retcod dint vl v2 3 eee oon Vu beats 4 42 retcod dmul vl v2 ce err PEA due 4 42 retcod dsgn vl sss ss sss esse resse enhn n 4 42 retcod dsub vl v2 eee enn 4 42 retcod dtoa dvar str es rss 443 intval dtoi fvar wr TP iun ipu e 4 43 retcod dtof dvar fvar w ccccescesccceseccee ewe 4 43 BXIt COUS 2125 5 ves XO AR wee 4 94 retcod fabs vl v2 3 eee soon 4 49 retcod faud vl V2 TTT 4 49 retcod fatn Vl V2 Jia eO 4 49 retcod fclose fp aes aga geng R e EX RS HII L retcou femmi vl V2 TTT 4 49 retcod fcos vl v2 3 eee AAY retcod fdiv vl v2 pierna rn 6 40 retcod fexp vl v2 Dua p LEAN Gale EE 4 49 retcod ffix vl v2 Ee C pP E s 4 40 eofind fgets buf max fd eccoccsssscececeececcee SMG fillt buffer count char oz wis XV ii 4 34 retcod fint vl v2 IS naa e 4 49 retcod flog vl v2 var S A un REUS 4 4 retcod fmul vl v2 eene abs 4 49 fp fopen fspec mode aaas cede sees 4 97 fpinit 56 9 96006460990 2 50 06020944099 5 0s00 92925 902 999062929282 206 IP 4 39 retcod fraise vl v2 sesa sassa aeaaeae e sce 4 49 retcod fprintf fp control argl arg2 4 88 retcod fputs string fp oooooooomoomonooo o soe 4 99 free ptr aT
154. x the object except the increment and decrement operators The and may appear after postfix the object also The term lvalue means an expression which evaluates to the address of a data element or pointer field Constants function identifiers and array names are not lvalues The term derives from the observation that lvalues are the only expressions allowed on the left side of an assignment expression T The indirection operator can only operate on a pointer expression Its meaning is effectively object at The address contained in the pointer is the address of the object referred to by this type of expression For example See pointer pointer t pointer a character pointer first print the address passed in pointer printf address is Xd pointer now print the data at that address printf data is Xd pointer will print both the address contents of the pointer variable and the data at that address result of the indirect expression UNARY OPERATORS _ 2 17 MS LANGUAGE DEFINITION This unary operator effectively means address of or pointer to It evaluates to the address of the lvalue it precedes When the unary negation operator precedes an expression the result is the two s complement negative of the value of the expression When the precedes an unsigned or pointer expression the one s complement of the value is taken Since all expression
Download Pdf Manuals
Related Search
Related Contents
Español - ResMed Chapitre D1 - LEVÉS OFFICIELS - 404 Uniden EXP7900 Owner's Manual Installation 5 USER MANUAL - Boiance™ Float 皆さん、 はじめまして。 CDS株式会社です。 当社は、 最新の ー 丁技術を dbCitations User Manual Samsung A+ Copyright © All rights reserved.
Failed to retrieve file