Home
C for AIX User's Guide
Contents
1. 345 Appendix D Preprocessor Directives and Related Information 347 List of Standard Preprocessor Directives 2 ee eee ee ee we B47 Null Preprocessor Directive 2 a ee ee eee ee B47 define Preprocessor Directive 2 2 2 ee eee ee ee we B48 if elif Preprocessor Directives 1 1 ee ee ee ee eee 852 else Preprocessor Directive 2 1 1 we eee ee ee ee ee ee BKB endif Preprocessor Directive 1 1 we ee ee ee ee ee 858 error Preprocessor Directive 1 ee ee ee ee ee ee ee ee 854 ifdef Preprocessor Directive 1 1 we ee ee ee ee ee ee BBS indef Preprocessor Directive 1 ee ee ee ee ee ee ee 955 include Preprocessor Directive 2 1 2 eee ee ee ee ee B56 line Preprocessor Directive 2 ww ee ee ee ee ee ee B57 undef Preprocessor Directive 2 1 we ee ee ee ee ee ee B58 Predefined Preprocessor Macros ee eee ee eee eee ee ee ee Od Examples of Predefined Macros in a Program _eteer eae eee ee ee we ee em FOE pragma Preprocessor Directives 2 1 ee ee ee ee ee 863 pragma alloca Preprocessor Directive 1 we ee ee ee ee 365 pragma chars Preprocessor Directive 1 ee ee ee ee ee ee 865 pragma comment Preprocessor Directive 2 eee ee ee ee 366 pragma disjoint Preprocessor Directive cou ew oe ke Se ee oe ow Se ee we OO
2. Examples of Eumerator Declaration and Use The following data type declarations list oats wheat barley corn and rice as enumeration constants The number under each constant shows the integer value Chapter 6 The C Language 83 enum grain oats wheat barley corn rice 0 1 2 3 4 enum grain oats 1 wheat barley corn rice 1 2 3 4 5 enum grain oats wheat 10 barley corn 20 rice 0 10 11 20 21 It is possible to associate the same integer with two different enumeration constants For example the following definition is valid The identifiers suspend and hold have the same integer value enum status run clear 5 suspend resume hold 6 Js 0 5 6 7 6 The following example is a different declaration of the enumeration tag status enum status run create clear 5 suspend 0 1 5 6 The following program receives an integer as input The output is a sentence that gives the French name for the weekday that is associated with the integer If the integer is not associated with a weekday the program prints C est le mauvais jour xx Example program using enumerations include lt stdio h gt enum days Monday 1 Tuesday Wednesday Thursday Friday Saturday Sunday weekday void french enum days int main void int num printf Enter an integer for the day of the week Mon 1 Sun 7 n scanf d amp num weekday num french weekday return
3. Map the file to this process address space starting at an address that should also be available in child processe s hMap MapViewOfFileEx hFile FILE MAP WRITE 0 0 BASE MEM info pBase hMap if info pBase NULL return NULL Create a fixed sized heap Put the heap handle as well as the base heap address at the beginning of the shared memory info pHeap _ucreate char info pBase sizeof info heap size sizeof info BLOCK CLEAN _HEAP_SHARED HEAP REGULAR NULL NULL if info pBase NULL return NULL memcpy info pBase info sizeof info if _uopen info pHeap Open heap and check result return NULL return info pHeap es termhp Function to close and destroy the heap 27 7 7 static int termhp Heap_t uheap if _uclose uheap close heap return 1 if _udestroy uheap _FORCE force destruction of heap return 1 UnmapViewOfFile hMap return memory to system CloseHandle hFile return 0 lt MMIII main 192 C for AIX Users Guide x x Main function to test creating writing to and destroying a shared heap 22 int main void int i rc Index and return code Heap _t uheap heap to create void init_block initial block to use char p for allocating from heap call init function to create and open the heap uheap inithp
4. Double quotation mark Mf Question mark Backslash The value of an escape sequence represents the member of the character set used at run time Escape sequences are translated during preprocessing For example the AIX Version 4 operating system uses the ASCII character set where the value of the escape sequence x56 is the letter V Use escape sequences only in character constants or in string literals If an escape sequence is not recognized the compiler removes the backslash and issues a warning message For example the string abc def becomes abcdef Note that this behavior is implementation defined When a hexadecimal escape sequence is longer than two digits the compiler issues a warning Only the rightmost two digits are used For example in the following statement printf x06asset n only the digits 6a are retained In string and character sequences when you want the backslash to represent itself rather than the beginning of an escape sequence you must use a backslash escape sequence include lt stdio h gt void main char a b c d e a a b 97 ASCII integer value x c 141 ASCII octal value a d x61 ASCII hexadecimal value e n printf c c c c c n a b c d Related Reading Identifier Behavior in Your Program Scope of Identifier Visibility An identifier becomes visible with its declaration The region where an identifier is visible is
5. In the following example statements are not present If the value of text i is equal to A all three counters are incremented If the value of text i is equal to a lettera and total are increased Only total is increased if text i is not equal to A or a char text 100 int capa lettera total for i 0 i lt sizeof text i Switch text i case A Capat case a letteratt default total r The following statement performs the same statements for more than one case label int month Determine what season a month falls into Switch month case l2 case 1 case 2 printf month d is a winter month n month break case 3 case 4 case 5 printf month d is a spring month n month break case 6 case 7 case 8 printf month d is a summer month n month break case 9 case 10 case ll printf month d is a fall month n month break case 66 case 99 default printf month d is not a valid month n month If the expression month has the value 3 control passes to the statement printf month d is a spring month n month j Statement passes control to the statement following the Chapter 6 The C Language 157 Related Reading while A while statement repeatedly runs the body of a loop until the controlling expression evaluates to 0 e while expression staternent id The expression is evalu
6. Indirection The indirection operator determines the value referred to by the pointer type operand The operand cannot be a pointer to an incomplete type The operation yields an Ivalue or a function designator if the operand points to a function Arrays and functions are converted to pointers The type of the operand determines the type of the result For example if the operand is a pointer to an int the result has type int Do not apply the indirection operator to any pointer that contains an address that is not valid such as NULL The result is not defined If p_to_y is defined as a pointer to an int and y as an int the expressions p_to_y ay p_ to y 3 cause the variable y to receive the value 3 Cast type_name Type Casting A cast operator converts the type of the operand to a specified data type and performs the necessary conversions to the operand for the type The cast operator is a type specifier in parentheses This type and the operand must be scalar The type can also be void The result has the type of the specified data type but is not an lvalue The following expression contains a cast expression double x to convert an operand of type int to a value of type double int xX printf x 1f n double x The function printf receives the value of x as a double The variable x remains unchanged by the cast 122 C for AIX User s Guide sizeof Size of an Object The sizeof operator yi
7. Syntax Appendix E Parallel Processing Facilities 385 pragma ibm permutation identifier identifier lt countable for while do loop gt where identifier represents the name of an array Notes identifier cannot be the name of a pointer An array specified by this pragma cannot be a function parameter Related Reading pragma ibm schedule Preprocessor Directive The schedule pragma specifies the scheduling algorithms used for parallel processing Syntax pragma ibm schedule sched type lt countable for while do loop gt where sched type represents one of the following options affinity lterations of a loop are initially divided into local partitions of size affinity n ceiling number_of_iterations number_of_threads Each local partition then further subdivided into chunks of size ceiling number_of_iterations_remaining_in_partition 2 If n is specified each local partition is subdivided into chunks of size n where n is an integral assignment expression of value 1 or greater When a thread becomes available it takes the next chunk from its local partition If there are no more chunks in the local partition the thread takes an available chunk from the partition of another thread dynamic If n is not specified iterations of a loop are divided into chunks of size 1 dynamic n o l If n is specified all chunks are set to size n where nis an integral assignment expression of value 1 or greater
8. The reconstructed source line represents the line as it appears after macro expansion At times the line may be only partially reconstructed The characters at the start or end of the displayed line indicate that some of the source line has not been displayed The default nosrcmsg displays concise messages that can be parsed Instead of giving the source line and pointers for each error a single line is displayed showing the name of the source file with the error the line and character column position of the error and the message itself Example To compile myprogram c so that the source line is displayed along with the diagnostic message when an error occurs enter xlc myprogram c qsrcmsg Related Reading statsym Option Type Default Value pragma options fp aoptin frosts Syntax qstatsym qnostatsym 324 C for AIX User s Guide Purpose Adds user defined nonexternal names that have a persistent storage class such as initialized and uninitialized static variables to the name list the symbol table of xcoff objects Default The default is to not add static variables to the symbol table However static functions are added to the symbol table Example To compile myprogram c so that static symbols are added to the symbol table enter xlc myprogram c qstatsym Related Reading stdinc Option Type Default Value pragma options Syntax qstdinc qnostdinc STDINC NOSTDINC Purp
9. Use the qidirfirst option with the include file_name directive to search the directories specified with the Idirectory option before searching other directories Use the I option to specify the directory search paths Related Reading Or DdOe d Using Memory Heaps in a Program Memory Management Functions The memory management functions defined by ANSI are calloc malloc realloc and free These regular functions allocate and free memory from the default runtime heap C for AIX includes another function heapmin to return unused memory to the system C for AIX also provides enhanced versions of memory management functions that can help you improve program performance link to the libhm a library work with user heaps or debug your programs All the versions actually work the same way They differ only in what heap they allocate from and in whether they save information to help you debug memory problems The memory allocated by all of these functions is suitably aligned for storing any type of object The table below summarizes the different versions of memory management functions using malloc as an example of how the names of the functions change for each version Regular Version Debug Version Default Heap malloc _debug_ malloc User Created Heap _umalloc _debug_umalloc Chapter 7 Writing C Programs 179 Heap Specific Functions Use heap specific versions of memory allocation functions to allocate and free memor
10. Within nested statements the continue statement ends only the current iteration of the do for or while statement immediately enclosing it Restrictions A continue statement can only appear within the body of an iterative statement Related Reading aD Q VAQ J NOUe on nade a Examples Using the continue Statement The following example shows a continue statement in a for statement The continue statement causes processing to skip over those elements of the array rates that have values less than or equal to 1 xx This example shows a continue statement in a for statement include lt stdio h gt define SIZE 5 int main void int i static float rates SIZE 1 45 0 05 1 88 2 00 0 75 printf Rates over 1 00 n Chapter 6 The C Language 147 for i 0 i lt SIZE i if rates i lt 1 00 skip rates lt 1 00 continue printf rate 2f n rates i return Q The program produces the following output Rates over 1 00 rate 1 45 rate 1 88 rate 2 00 The following example shows a continue statement in a nested loop When the inner loop encounters a number in the array strings that iteration of the loop ends Processing continues with the third expression of the inner loop The inner loop ends when the 0 escape sequence is encountered Ikk xx This program counts the characters in strings that are part xx of an array of pointers to characters T
11. e The highest severity level of all errors diagnosed is less than the setting of the qhalt compiler option and the number of errors did not reach the limit set by the qmaxerr compiler option Otherwise the compiler sets the return code to one of the following values Return Code Error Type Any error with a severity level higher than the setting of the halt compiler option has been detected An option error or an unrecoverable error has been detected A configuration file error has been detected 250 An out of memory error has been detected The xlc command cannot allocate any more memory for its use 251 A signal received error has been detected That is an unrecoverable error or interrupt signal has occurred 252 A file not found error has been detected 253 An input output error has been detected files cannot be read or written to 254 A fork error has been detected A new process cannot be created 20 C for AIX Users Guide 255 An error has been detected while the process was running Related Reading Compiler Message Format Diagnostic messages have the following format when the Fsremsg on page 324 option is active which is the default file line line_number column_number 15dd nnn severity text where file is the name of the C source file with the error line_ number is the line number of the error column_number is the column number for the error 15 is the compiler product identifier CC is a
12. e The storage duration for the object is static storage is maintained throughout program run time or automatic storage is maintained only during the execution of the block where the object is defined For a function the storage class specifier determines the linkage of the function Declarations with the auto or register storage class specifier result in automatic storage Those with the extern or static storage class specifier result in static storage Most local declarations that do not include the extern storage class specifier allocate storage however function declarations and type declarations do not allocate storage The only storage class specifiers allowed in a global or file scope declaration are static and extern Storage class specifier keywords are e auto e extern e register e static e typedef Related Reading Initializers An initializer is an optional part of a data declaration that specifies an initial value of a data object Pe EXPrSSSION Si ne The initializer consists of the symbol followed by an initial expression or a braced list of initial expressions separated by commas The number of initializers must not be more than the number of elements to be initialized An initializer list with fewer initializers than elements can end with a comma indicating that the rest of the uninitialized elements are initialized to zero The initial expression evaluates to the first value of the data object
13. not accepted The rules concerning apply whether or not the directive is valid For example define M 1 not allowed def ine M 1 not allowed define M 1 allowed dfine M 1 equivalent to dfine M 1 even though dfine is not valid 288 C for AIX User s Guide Following are the preprocessor directive differences between classic mode and ansi mode Directives not listed here behave similarly in both modes ifdef ifndef When the first token is not an identifier no diagnostic message is generated and the condition is FALSE else When there are extra tokens no diagnostic message is generated endif When there are extra tokens no diagnostic message is generated include The lt and gt are separate tokens The header is formed by combining the spelling of the lt and gt with the tokens between them Therefore and are recognized as comments and are always stripped and the and do begin literals within the lt and gt Remember that in C programs C style comments are recognized when qcpluscmt is specified 1ine The spelling of all tokens which are not part of the line number form the new file name These tokens need not be string literals error Not recognized in classic mode define A valid macro parameter list consists of zero or more identifiers each separated by commas The commas are ignored and the parameter list is constructed as if they were not
14. return 0 Related Reading usepcomp Option Type Default Value pragma options aopton nousepcome Syntax qusepcomp qusepcomp directory qnousepcomp Purpose Uses a precompiled header file if no included files that have not changed since the precompiled header was created This may help improve compile time Notes Usage modes for usepcomp are qusepcomp Uses the precompiled header file called csetc pch if it exists in the current directory qusepcomp directory Uses a precompiled header file if e directory is the name of an existing directory and the csetc pch precompiled header file exists in that directory e a directory with the name directory does not exist but a precompiled header file called directory exists in the current directory qnousepcomp Does not use precompiled header files The qusepcomp and qgenpcomp options are designed to be used together but they may be used separately e qgenpcomp used alone will refresh the contents of the precompiled header file even if it already exists This is useful if the file has been corrupted e qusepcomp used alone will use an existing precompiled header file without creating a new one This is useful if you only want do not want the precompiled header file to be recompiled or if remaining disk space Is low When qusepcomp and qgenpcomp are used together the compiler will automatically maintain and use a current precompiled header Appendix A
15. Chunks are assigned to threads on a first come first serve basis as threads become available This continues until all work is completed guided Chunks are made progressively smaller until the default minimum chunk size is reached The guided n first chunk is of size ceiling number_of_iterations number_of_threads Remaining chunks are of size ceiling number_of_iterations_remaining number_of_threads If n is specified the minimum chunk size is set to n where n is an integral assignment expression of value 1 or greater If n is not specified a default value of 1 is assumed Chunks are assigned to threads on a first come first serve basis as threads become available This continues until all work is completed runtime Scheduling policy is determined at run time 386 C for AIX User s Guide static Iterations of a loop are divided into chunks of size ceiling number_of_iterations number_of_threads Each thread is assigned a separate chunk This scheduling policy is also known as block scheduling Iterations of a loop are divided into chunks of size n Each chunk is assigned to a thread in Static n round robin fashion n must be an integral assignment expression of value 1 or greater This scheduling policy is also known as block cyclic scheduling static 1 Iterations of a loop are divided into chunks of size 1 Each chunk is assigned to a thread in round robin fashion This scheduling policy is also known as cyclic scheduling Notes
16. Example To compile mypascal c and convert string literals into null terminated strings enter xlc mypascal c qmacpstr Related Reading maf Option Type Default Value pragma options Syntax qmaf qnomaf MAF NOMAF Purpose Specifies whether floating point multiply add instructions are to be generated This option affects the orecision of floating point intermediate results Before using this option see Options on page 271 for more information about floating point operations Appendix A Compiler Options 297 Notes This option is obsolete Use qfloat maf in your new applications makedep Option Type Default Value pragma options a E Syntax qmakedep Purpose Creates an output file that contains targets suitable for inclusion in a description file for the AIX make command Notes The qmakedep option is functionally identical to the M option U files are not make files u files must be edited before they can be used with the make command For more information on this command see AIX Version 4 Commands Reference If you do not specify the o option the output file generated by the qmakedep option is created in the current directory It has a u suffix For example the command xlc qmakedep person years c produces the output file person_years u A u file is created for every input file with a c or i suffix Output u files are not created for any other files For example the comma
17. Implementation Dependency Arrays and Pointers F 3 7 Implementation Dependency Registers F 3 8 Implementation Dependency Structures Unions Enumerations Bit Fields A 6 3 9 F 3 9 Implementation Dependency Qualifiers F 3 10 Implementation Dependency Declarators F 3 11 Implementation Dependency Statements F 3 12 Implementation Dependency Preprocessing Directives F 3 13 Implementation Dependency Library Functions F 3 14 Implementation Dependency Locale Specific Behavior F 4 Type Conversions ME E Xil C for AIX User s Guide 396 397 397 398 399 x 399 400 402 404 407 407 408 410 412 413 415 416 417 419 421 422 423 425 426 428 430 431 435 437 438 438 440 442 445 445 445 446 447 448 448 449 451 452 452 453 453 454 454 454 455 459 461 Synchronization of Stores and Loads to I O Space Example of Multiple Writes to a Single Register Example of Reading and Writing to Mapped to O Space l Appendix J C for AIX and XL C Compatibility Appendix K National Languages Support in the C for AIX Compiler Converting Files Containing Multibyte Data to New Code ka Where Multibyte Characters Are Supported 4 Appendix L C for AIX Files l etc vac cfg Default Configuration File vac cfg 41 Compiler Configuration File vac cfg 43
18. Preprocessor Output Example 1 For the following source code fragment int a int b A comment that spans two physical source lines ine C This is a C comment int d The output for the P option is int a int b int C int d The ANSI mode output for the P Coptions is int a int b A comment that spans two physical source lines int C This is a C comment int d The output for the E option is int a int b int C int d The ANSI mode output for the E C options is line 1 fred c int a int b a comment that spans two physical source lines Int Ci This is a C comment int d Extended mode output for the P C options or E C options is int a int b A comment that spans two physical source lines Int C This is a C comment int d Preprocessor Output Example 2 Directive Line For the following source code fragment int a define mm 1 This is a C comment on which spans two physical source lines int b This is a C comment int C The output for the P option is 248 C for AIX User s Guide int a int b int c The output for the P C options int a int b This is a C comment int C The output for the E option is line 1 fred c int a line 4 int b int C The output for the E C options line 1 fred c int a line 4 int b This is a C comment int C Preprocessor Output Example 3 Macro Function A
19. Related Reading define Preprocessor Directive A preprocessor define directive directs the preprocessor to replace all subsequent occurrences of a macro with specified replacement tokens e define denier idendiher e bese TIENITI 348 C for AIX User s Guide The define directive can contain an object like definition or a function like definition Object Like Macros An object like macro definition replaces a single identifier with the specified replacement tokens The following object like definition causes the preprocessor to replace all subsequent instances of the identifier COUNT with the constant 1000 define COUNT 1000 If the statement int arry COUNT appears after this definition and in the same file as the definition the preprocessor would change the statement to int arry 1000 in the output of the preprocessor Other definitions can make reference to the identifier COUNT define MAX COUNT COUNT 100 The preprocessor replaces each subsequent occurrence of MAX_COUNT with COUNT 100 which the preprocessor then replaces with 1000 100 If a number that is partially built by a macro expansion is produced the preprocessor does not consider the result to be a single value For example the following will not result in the value 10 2 but in a syntax error define a 10 a 2 Using the following also results in a syntax error define a 10 define b a 1l To have the
20. Scheduling algorithms for parallel processing can be specified using any of the methods shown below If used methods higher in the list override entries lower in the list e pragma statements e compiler command line options e run time command line options e run time default options Scheduling algorithms can also be specified using the schedule argument of the parallel_ loop pragma statements For example the following sets of statements are equivalent pragma ibm schedule guided 10 pragma ibm parallel loop for i 0 i lt N i and pragma ibm parallel loop schedule guided 10 for i 0 i lt N i If different scheduling types are specified for a given loop the last one specified is applied Related Reading pragma ibm sequential_loop Preprocessor Directive The sequential_loop pragma explicitly instructs the compiler to execute the chosen loop sequentially Syntax pragma ibm sequential loop lt countable for while do loop gt Appendix E Parallel Processing Facilities 387 Notes This pragma disables automatic parallelization of the chosen loop and is always respected by the compiler Related Reading pragma omp parallel Preprocessor Directive The omp parallel directive explicitly instructs the compiler to parallelize the chosen segment of code When a parallel region is encountered a logical team of threads is formed Each thread in the team executes all statements within a p
21. The usual arithmetic conversions on the operands are performed Addition The addition operator yields the sum of its operands Both operands must have an arithmetic type or one operand must be a pointer to an object type and the other operand must have an integral type When both operands have an arithmetic type the usual arithmetic conversions on the operands are performed The result has the type produced by the conversions on the operands and is not an Ivalue A pointer to an object in an array can be added to a value having integral type The result is a pointer of the same type as the pointer operand The result refers to another element in the array offset from the original element by the amount specified by the integral value If the resulting pointer points to storage outside the array other than the first location outside the array the result is undefined The compiler does not provide boundary checking on the pointers For example after the addition ptr points to the third element of the array int array 5 int ptr ptr array 2 Subtraction The subtraction operator yields the difference of its operands Both operands must have an arithmetic type or the left operand must have a pointer type and the right operand must have the same pointer type or an integral type You cannot subtract a pointer from an integral value When both operands have an arithmetic type the usual arithmetic conversions on the operands
22. ampersand 39 40 4 N N apostrophe O1 NO 00 left parenthesis k Ol NO right parenthesis D NO NO gt asterisk D oo NO UW addition sign D 4 45 46 O1 N O comma O1 O1 U subtraction sign O1 oO NO m period right slash D 00 ee O D co O oo hk O1 OD NO oO NO Ol OD oe 09 ee O1 NO O oe D O1 oO OD O1 oO O1 O1 Q O O1 O1 oO NJ ee N IS O1 or o AK D K L J WIN D No Po PO Po O1 O N Q 00 se a o fen SSS Cs n s o o Co n o oo e o e o o we 7 a o o SSS at sign 64 5 100 101 40 4 4 4 4 45 4 4 O NO 7 oO 104 105 106 107 N 0 NJ O ak k oO N N A 00 A O S gt x lt C D D o O C Q D TT a esf o o e a a a a Bme ssj K oe omg ee e a a e a PR e a a a e r a eof w a foo ee pee e e s s o 5 ooo e e ee ey a7 e se 130 0 58 o ee e e ee e a _ T a left bracket left slash backslash right bracket hat circumflex caret underscore grave accent ice NJ D h e oh 142 e d es Jooo ed woo f ae oe oo a a g os d s o e d oe f oe oee o s ow a o o d EC e a a a a e h i Appendix M ASCII Character Set 485 a ee a DD e one f iws a o e DG ons e g o y e a a a a 2 e r ls pat
23. and cannot be privatized pragma omp parallel firstprivate p int b private automatic static int s shared static x pragma omp for for i 0 int tmp b b is still private here foo i i is private here because it is an iteration variable pragma omp parallel int tmp b b is shared here because it is another parallel region int E2 shared static void foo int x x is private for the parallel region it was called from x int C the same Some OpenMP preprocessor directives let you explicitly specify visibility context for selected data variables For more information see OpenMP directive descriptions or the OpenMP C and C Application Program Interface specification Note that even if a variable has shared context it can be privatized by the compiler if it is possible to do so without changing the semantics of the program For example if each loop iteration uses a unique value of a shared variable that variable can be privatized Privatized variables are reported by the qinfo private option Related Reading Using Pragmas to Control Parallel Processing Parallel processing operations are controlled by pragma directives in your program source You can use either IBM or OpenMP parallel processng directives Each have their own usage characteristics IBM Directives Chapter 5 Program Parallelization 41 Syntax pragma ibm pragma_name_and_
24. e The overhead for the function is significant for example when functions are called within nested loops e The inlined function provides additional opportunities for optimization such as when constant arguments are used For example given the following function void glen int a int b if a 10 switch b case 1 case 20 puts b is 20 break case 30 202 C for AIX User s Guide default and assuming your program calls glen several times with constant arguments for example glen 10 20 each call to glen causes the if and switch expressions to be evaluated If glen is inlined the compiler can then optimize the function The evaluation of the if and switch statements can be done at compile time and the function code can then be reduced to only the puts statement from case 20 The best candidates for inlining are small functions that are called often Use the Performance Analyzer or a profiler to determine which functions to inline to obtain the best results Drawbacks of Inlining Inlining user code usually results in a larger executable module because the code for the function is included at each call site Because of the extra optimizations that can be performed the difference in size may be less than the size of the function multiplied by the number of calls Inlining can also result in slower program performance especially if you use auto inlining Because auto inlining looks only at the number o
25. heapdebug hsflt hssngl le x idirfirst ignerrno ignprag info initauto inlglue inline ipa isolated call L i oe ee me 4 langivl Idol128 longdouble libansi linedebug list listopt longlit longlong 240 240 241 242 242 243 244 245 246 247 290 251 252 252 253 293 253 259 258 lt 299 259 260 261 261 264 265 266 266 267 267 268 269 2 0 2 1 212 2 2 21 3 214 214 275 27 6 21 1 2f 279 284 285 286 286 289 290 291 291 292 292 293 294 Contents ix Ma es ee ke ee eee ee ee eee eee ee hee kee eee ee aA Maceo as amp ess kt ee eS Bee eee ee ee we be eee ew ee wo Mele ts eee pA Re eee eee eee ke Ok ee be oe ee ee oe eS ee makedep 2 me Be SE Se eS we ee eo ew ese ee oe ee Se ee we A a 298 MaX e e w d Ae hee ee ee ee Fh ob we ee eh a ek hk oe ee Re ee MAXMO s s s s s a ee rp p Re ow eee we se ee ee Ewe s s oe oe we a a a 000 mbcs docs a a a a a eee 80 DODI a 4a ea ts we Ewe ee ee ee ee eh ee ha oe ae ee me ee OT O optimize amp ww amp eb we a De we we amp amp we 2 302 One caeeoeweeaktenkaeewpeeweeebeueeu Rw aeveaueeaeaea a 00 OCG eu Bee eee peek whe tteuhueeehree tet amp B amp H amp amp 6 OOD Pawmeehe ewe ee ee ee eee eee ee ea ee ew ee ee ee ee eS wor Deus
26. 3 25 printf passed var d n passed var 26 This program produces the following output 2 inner auto var passed var 1 passed var 3 outer auto var 1 The following example uses an array that has the storage class auto to pass a character string to the function sort The function sort receives the address of the character string rather than the contents of the array The address enables sort to change the values of the elements in the array ERK RRR KKK KERR EKER ERR ERR EK RE RRR KK EKER EKER RRR EKER ER ERR k Kk ERR EKER Kk EK xx Sorted string program this example passes an array name xx to a function KK KKK KK KK ERK kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk include lt stdio h gt include lt string h gt int main void void sort char array int n char string 75 int length printf Enter letters n scanf 74s string length strlen string sort string length printf The sorted string is s n string return 0 void sort char array int n int gap i j temp for gap n 2 gap gt 0 gap 2 for i gap i lt n i for j i gap j gt 0 amp amp array j gt array j gap 7 j gap temp array j array j array j gap array j gap temp When the program is run interaction with the program could produce Output Enter letters Input zyfab Output The sorted string is abfyz Related Reading Fauto
27. 64 Sets the compiler to generate and or use 64 bit objects 32 64 Sets the compiler to accept both 32 and 64 bit objects The compiler never functions in this mode and 7 using this choice may generate an error message depending on other compilation options set at compile time 54 bi omoilation on page 14 for more information Setting Parallel Processing Run time Options The XLSMPOPTS environment variable sets options for programs using loop parallelization For example to have a program run time create 4 threads and use dynamic scheduling with chunk size of 5 you would set the XLSMPOPTS environment variable as shown below XLSMPOPTS PARTHDS 4 SCHEDULE DYNAMIC 5 Additional environment variables set options for program parallelization using OpenMP compliant directives Setting Environment Variables for the Message and Help Files Before using the compiler you must install the message catalogs and help files and set the following two environment variables LANG Specifies the national language for message and help files NLSPATH Specifies the path name of the message and help files The LANG environment variable can be set to any of the locales provided on the system See the description of locales in AIX General Programming Concepts for IBM RISC System 6000 for more information Copyright IBM Corp 1995 1999 3 The national language code for United States English is en_US If the appropriate message catalogs h
28. Notes The qbitfields suboptions are Signed Bitfields are signed unsigned Bitfields are unsigned Related Reading Option Type Default Value pragma options e Syntax brt Purpose Tells the linkage editor to perform library searches of both a and so library files 240 C for AIX User s Guide Notes This option affects all library searches For a library name and path specied by the I and L options the linkage editor searches if they exist the SO library first and then the a library Example To compile myprogram c searching both shared and static versions of the C for AIX compiler libraries enter xlc myprogram c brt Related Reading bstatic bdynamic Option Type Default Value pragma options stag beynaio Syntax bstatic bdynamic Purpose Controls how libraries are processed by specifying which forms of library names the linkage editor looks for Notes The linkage editor searches library names and paths specied by the I and L options according to the following criteria bdynamic For settings of the lkey option appearing after the bdynamic option both libkey so and libkey a library files are searched for by the linkage editor This option remains in effect until overridden by the appearance of the bstatic option which in turn affects lkey options appearing after it bstatic For settings of the lkey option appearing after the bstatic option only libkey a library files are sea
29. Right Operand Or Arithmetic Arithmetic Pointer Integral type x and Arithmetic Arithmetic lt lt gt amp 2 and Integral type Integral type Note that the expression a b c is equivalent to a a b c and nota a b c Related Reading Examples Using Compound Assignment Operators The table below lists the compound assignment operators and shows an expression using each operator Operator Example SSSSSCgulvalent Expression i e pointers 1 pointer pointer 2 allowance allowance 1000 oe s Chapter 6 The C Language 135 test pre test test test pre test Although the equivalent expression column shows the left operands from the example column evaluated twice the left operand is evaluated only once Related Reading Comma Operator A comma expression contains two operands separated by a comma Although the compiler evaluates both operands the value of the right operand is the value of the expression The left operand is evaluated possibly producing side effects and the value is discarded The result of a comma expression is not an lvalue Both operands of a comma expression can have any type All comma expressions have left to right associativity The left operand is fully evaluated before the right operand In the following example if omega has the value 11 the expression increments delta and assigns the
30. To assign a value to a scalar object use the simple initializer expression For example the following data definition uses the initializer 3 to set the initial value of group to 3 int group 3 Chapter 6 The C Language 65 For unions and structures the set of initial expressions must be enclosed in braces unless the initializer is a string literal If the initializer of a character string is a string literal the are optional Individual expressions must be separated by commas and groups of expressions can be enclosed in braces and separated by commas In an array structure or union initialized using a brace enclosed initializer list any members or subscripts that are not initialized are implicitly initialized to zero of the appropriate type The initialization properties of each data type are described in the section for that data type In the following example only the first eight elements of the array grid are explicitly initialized The remaining four elements that are not explicitly initialized are initialized as if they were explicitly initialized to zero static short grid 3 4 0 0 0 1 0 0 1 1 The following example is an equivalent initialization of the array grid static short grid 3 4 0 0 0 1 10505 Ie Iji The initial values of grid are a a e S rift rte riofot a e E a a T a grid 0 3 rigid rifts rset ia rset Related Reading Type Specifiers
31. X 1 0 y 3 0 x x y3 ij int amp x printf 1 3 8x n i is compiled with xlc yz qfloat rndsngl the expression 1 0 3 0 is folded by the compiler at compile time into a double precision result This result is then converted to single precision and then stored in float x The float nofold option can be specified to suppress all compile time folding of floating point computations The yz option only affects compile time rounding of floating point computations but does not affect runtime rounding The code fragment 1 0 3 0 x y X y X is evaluated at run time in single precision Here the default runtime rounding of round to nearest is still in effect and takes precedence over the compile time specification of round to zero yz Note The y option does not specify the runtime rounding mode Related Reading Floating Point Compiler Options Compiler options affect the accuracy performance and potentially the correctness of floating point calculations Although the default values for the options have been chosen to provide efficient and correct execution of most programs some applications may require nondefault options to reproduce results reported by other hardware You should read this and related pages before using the floating point options By default the C for AIX compiler produces object code that evaluates floating point expressions in double precision even if all operand
32. You can then allocate and free from your own heap just as you would from the default heap To allocate memory use _ucalloc or umalloc These functions work just like calloc and malloc except you specify the heap to use as well as the size of block that you want For example to allocate 1000 bytes from fixedHeap void up up _umalloc fixedHeap 1000 To reallocate and free memory use the regular realloc and free functions Both of these functions always check what heap the memory came from so you don t need to specify the heap to use For example the realloc and free calls in the following code fragment look exactly the same for both the default heap and your heap void p up p malloc 1000 allocate 1000 bytes from default heap up _umalloc fixedHeap 1000 allocate 1000 from fixedHeap realloc p 2000 reallocate from default heap realloc up 100 reallocate from fixedHeap free p free memory back to default heap free up free memory back to fixedHeap x For any object you can find out what heap it was allocated from by calling mheap You can also get information about the heap itself by calling ustats which tells you e How much memory the heap holds excluding memory used for overhead e How much memory is currently allocated from the heap e What type of memory is in the heap e The size of the largest contiguous piece of memory available from the heap When you call any hea
33. alili cli alitl b it 1 clitl ali 2 b i 2 c i 2 if i lt n remainder for i lt n i alij b i cli Related Reading upconv Option Type Default Value pragma options Syntax qupconv qnoupconv UPCONV NOUPCONV Purpose Preserves the unsigned specification when performing integral promotions Notes The qupconv option promotes any unsigned type smaller than an int to an unsigned int instead of to an int Unsignedness preservation is provided for compatibility with older dialects of C The ANSI C standard requires value preservation as opposed to unsignedness preservation Default The default is qnoupconv except when qlanglvl ext in which case the default is qupconv The compiler does not preserve the unsigned specification The default compiler action is for integral promotions to convert a char short int int bitfield or their signed or unsigned types or an enumeration type to an int Otherwise the type is converted to an unsigned int 334 C for AIX User s Guide Example To compile myprogram c so that all unsigned types smaller than an int are converted to unsigned int enter xlc myprogram c qupconv The following short listing demonstrates the effect of qupconv include lt stdio h gt int main void unsigned char zero 0 if 1 lt zero printf Value preserving rules in effect n else printf Unsignedness preserving rules in effect n
34. smplibraries 1xlsmp optlibraries 1 xlopt resexp usr vacpp lib res exp genexports usr vac bin CreateExportList Appendix L C for AIX Files 481 482 cC for AIX Users Guide Appendix M ASCII Character Set The C for AIX compiler uses the American National Standard Code for Information Interchange ASCII character set as its collating sequence The following table lists the standard ASCII characters in ascending numerical order with their corresponding decimal octal and hexadecimal values It also shows the control characters with Ctrl notation For example the carriage return ASCII symbol CR appears as Ctrl M which you enter by simultaneously pressing the Ctrl key and the M key Decimal Octal Hex Value Control Character ASCII Value Value Symbol null of ps e os cmr Ack acknowedge OoOO O r o o o o o e om s e o n o o e ooa Cno e e om w ass D device control 3 D device control 4 N negative acknowledge S synchronous idle end of transmission block Des C4 NAK SYN ETB 24 cancel EM sub ESC O Fs substitute file separator 1 2 3 4 K N B N B C O S L C C C C A Y T A M U S escape S E end of medium F oO Copyright IBM Corp 1995 1999 48 we a e owsa Oooo Cs a a eretamaton pot Ca e e J o owego OO es e a pound sion umber sn Cso au a f s ows 37 45 25 7 percent sign os ekee e 1 oO oO
35. usr vac include string h usr vac include umalloc h Profile directed feedback library usr vac lib libpdf a Profiling library usr vac lib profiled Configuration file etc vac cfg Links to usr vac bin usr bin xic usr bin xlc128 usr bin xlc_r usr bin c89 usr bin cc usr bin cc128 usr bin cc_r Copyright IBM Corp 1995 1999 473 C for AIX Compiler Invocation Commands All invocation command files are placed in usr vac bin You may add this directory to the beginning of your PATH environment variable to make these commands available to you The default links in usr bin xlc cc c89 etc that point to usr vac bin of C for AIX are optional They are created at the discretion of the product installer using replaceCSET etc vac cfg Default Configuration File The C for AIX Compiler includes two versions of the default configuration file When you install the C for AIX Compiler only one of these configuration files is linked to etc vac cfg according to the following criteria e lf the level of your operating system is AIX 4 3 or higher etc vac cfg is linked to the vac cfg 43 default configuration file system is earlier than AIX 4 3 etc vac cfg is linked to the vac cfg 44 vac cfg 41 Compiler Configuration File COMPONENT NAME CC C for AIX Compiler FUNCTIONS C C Configuration file ORIGINS 27 C COPYRIGHT International Business Machines Corp
36. 1 play playl play2 play2 play2 1 Because the order of evaluation for subexpressions is not specified avoid using a variable more than once in an expression in which the variable is incremented For example the following expression might cause i to be incremented before or after the function x is called y x i itt The result has the same type as the operand after integral promotion but is not an Ivalue The usual arithmetic conversions on the operand are performed Decrement The decrement operator subtracts 1 from the value of a scalar operand or if the operand is a pointer decreases the operand by the size of the object to which it points The operand receives the result of the decrement operation The operand must be a modifiable lvalue You can put the before or after the operand If it appears before the operand the operand is decremented and the decremented value is used in the expression If the appears after the operand the current value of the operand is used in the expression and the operand is decremented For example play playl play2 is equivalent to the following three expressions playl playl 1 play playl play2 play2 play2 1 Because the order of evaluation for subexpressions is not specified avoid using a variable more than once in an expression in which the variable is decremented For example the following expression might cause i to be decremented b
37. Aggressive code motion and scheduling on computations that have the potential to raise an exception are allowed Loads and floating point computations fall into this category This optimization is aggressive because it may place such instructions onto execution paths where they will be executed when they may not have been according to the actual semantics of the program For example a loop invariant floating point computation that is found on some but not all paths through a loop will not be moved at O2 because the computation may cause an exception At O3 the compiler will move it because it is not certain to cause an exception The same is true for motion of loads Although a load through a pointer is never moved loads off the static or stack base register are considered movable at O3 Loads in general are not considered to be absolutely safe at O2 because a program can contain a declaration of a static array a of 10 elements and load a 60000000003 which could cause a segmentation violation The same concepts apply to scheduling Example In the following example at O2 the computation of b c is not moved out of the loop for two reasons a it is considered dangerous because it is a floating point operation b it does not occur on every path through the loop At O3 the code is moved int 1 float a 100 b c for i 0 i lt 100 i if aLi lt alit 1 ali btce Conformance to IEEE rules are rela
38. Global Register Allocation Allocates variables and expressions to available hardware registers using a graph coloring algorithm The O and Q compiler options also determine the types of inlining to be used Related Reading Special Handling of Math and String Library Functions The C for AIX compiler can improve optimization by generating substitute code for calls to some math and string functions available within the standard C runtime libraries The functions handled this way are defined as macros in usr include math h or usr include string h The special handling of these functions occurs by default when either math h or string h is included in the source program To explicitly generate substitute code for a particular function use the function with two underscores __strcpy for example When including math h and string h avoid redeclaring the functions If your application requires a function call to one or all of the math or string functions prevent special handling of all math or string functions within a source file by using either the U MATH _ or the U __STR__ option on the command line For example ixlc c U_MATH_ file c Runtime performance of an application is affected if special handling is disabled Related Reading Floating Point Operations with the C for AIX Compiler RISC System 6000 Floating Point Hardware The RISC 6000 floating point hardware performs all computations in IEEE double precision
39. Note Compiling your C for AIX programs with C for AIX The C for AIX compiler is a stricter compiler than the XL C compiler See Appendix ge 467 which discusses the issues you should consider if you plan to use your XL C programs with the C for AIX compiler C for AIX Compiler Limits The limits for your program might differ from those stated here depending on its complexity Nesting levels for included files 255 Significant initial characters in identifiers No limit but the linker has a limit of 4095 characters for external names Other system limits are set in the usr include sys limits h file The limits h header file is described in the Header Files Overview in the AIX Version 4 Files Reference Related Reading Implementation Defined Behavior Appendix F and other sections of the American National Standard for Information Systems Programming Language C X3 159 1989 standard designate several C language features as implementation defined The ANSI standard for the C language requires that manufacturers document the specifics of these features for their compiler This and related pages provide this ANSI required documentation and references the relevant sections of the ANSI standard The references are given in parentheses for each item for example 2 1 1 2 Copyright IBM Corp 1995 1999 445 Related Reading Appendix Impolem Implementation Dependency Translation F 3 1 Tran
40. Provides routines to enable disable and handle exceptions Exception handling includes the ability to identify the point where an exception occurred and to continue execution following an exception possibly supplying a value as the result of the failing instruction Two routines are visible enable fp traps mask x disable fp traps The names contain a trailing underscore to enable their use with the FORTRAN extname compiler option The flttrap compiler option will generate TRAP signals when floating point exceptions occur It does so by setting the record bit on all floating point instructions and then x trapping if condition register bit 5 is set that is if x the floating point enabled exception FEX bit is set in x the floating point status and control register include lt stdio h gt include lt stdlib h gt include lt signal h gt include lt fptrap h gt include lt fpxcp h gt The specific trap instruction used by the flttrap option is TRAP R15 R15 This is the machine code for that instruction define FLTTRAPINST 0x7c8f7808 The following table maps instruction bit patterns to the name x of a floating point instruction This table is referenced using bits 26 30 of a floating point instruction static char op table 32 femp at are a caer at a eg ga cae Aa en a ee a eae ee a ae mTYSD s at a a are 921 TIR at ae fa aar fs fa
41. Reference Output Files The linkage editor generates an executable file and places it in your current directory The default name for an executable file is a out To name the executable file explicitly use the ofile_name option with the xic command where file_name is the name you want to give to the executable file If you use the Ofile_name option the resulting executable file is called file_name Using the ld Command You can invoke the linkage editor explicitly with the Id command However the compiler invocation Chapter 3 Using the C for AIX Compiler 9 commands set several linkage editor options and link some standard files into the executable output by default In most cases it is better to use one of the compiler invocation commands to link edit your o files Note When link editing o files do not use the e option of the Id command The default entry point of the executable output is _ start Changing this label with the e flag can cause erratic results Related Reading Compiler Options Compiler options perform a wide variety of functions such as setting compiler characteristics describing the object code and compiler output to be produced and performing some preprocessor functions You can specify compiler options in one or more of three ways e on the command line e jin your source program e in a configuration file When specifying compiler options in more than one of the above locations it is possible for
42. Related Reading Example of Initialization within Statement Blocks The following program shows how the values of data objects change in nested statement blocks 1 include lt stdio h gt 2 3 int main void 4 5 int x 1 Initialize x to 1 Chapter 6 The C Language 159 6 int y 3 7 8 if y gt 0 9 10 int x 2 Initialize x to 2 11 printf second x 4d n x 12 13 printf first x 4d n x 14 The program produces the following output second x 2 first x 1 Two variables named x are defined in main The definition of x on line 5 retains storage while main is running However because the definition of x on line 10 occurs within a nested block line 11 recognizes x as the variable defined on line 10 Because line 13 is not part of the nested block x is recognized as the variable defined on line 5 Related Reading C Programming Character Set You can use any of the following characters from the ASCII character set to enter programming text into your source file abcdefghijgkImnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 Lee Lea a es lt gt _ e The space character e The control characters representing horizontal tab vertical tab and form feed Some characters from the C character set are not available in all environments You can enter these characters into a C source file using a sequences of two or three characters A sequence of three characters
43. Syntax qdpcl qnodpcl Purpose Generates symbols that tools based on the Dynamic Probe Class Library DPCL can use to see the structure of an executable file Notes When you specify the qdpcl option the compiler emits symbols to define blocks of code in a program You can then use tools that use the DPCL interface to examine performance information such as memory usage for object files that you have compiled with this option You must also specify the g option when you specify qdpcl You cannot specify the qipa or qsmp options together with qdpcl Related Reading Option Type Default Value pragma options a Syntax Appendix A Compiler Options 253 E Purpose Runs the source files named in the compiler invocation through the preprocessor The E option calls the preprocessor directly as usr vac exe xlCcpp Notes The E and P options have different results When the E option is specified the compiler assumes that the input is a C file and that the output will be recompiled or reprocessed in some way These assumptions are e Original source coordinates are preserved This is why line directives are produced e All tokens are output in their original spelling which in this case includes continuation sequences This means that any subsequent compilation or reprocessing with another tool will give the same coordinates for example the coordinates of error messages The P option is used for general pu
44. The preprocessor looks for the file defs h first in the directory that contains the source file If the file is not found there the preprocessor searches a sequence of specified or standard locations Example 2 In the following example a define combines several preprocessor macros to define a macro that represents the name of the C standard I O header file A include makes the header file available to the program define IQ HEADER lt stdio h gt include IO HEADER equivalent to specifying include lt stdio h gt Related Reading line Preprocessor Directive A preprocessor line control directive supplies line numbers for compiler messages It causes the compiler to view the line number of the next source line as the specified number Ft decimal constant i line Ye namng characters Appendix D Preprocessor Directives and Related Information 357 In order for the compiler to produce meaningful references to line numbers in preprocessed source the preprocessor inserts line directives where necessary for example at the beginning and after the end of included text A file name specification enclosed in double quotation marks can follow the line number If you specify a file name the compiler views the next line as part of the specified file If you do not specify a file name the compiler views the next line as part of the current source file The token sequence on a line directive is subject to macro replace
45. also assigns the value 3 to x 128 C for AIX Users Guide Bitwise AND The amp bitwise AND operator compares each bit of its first operand to the corresponding bit of the second operand If both bits are 1 s the corresponding bit of the result is set to 1 Otherwise it sets the corresponding result bit to 0 Both operands must have an integral type The usual arithmetic conversions on each operand are performed The result has the same type as the converted operands Because the bitwise AND operator has both associative and commutative properties the compiler can rearrange the operands in an expression that contains more than one bitwise AND operator The following example shows the values of a b and the result of a amp b represented as 32 bit binary numbers bit pattern of a 00000000000000000000000001011100 bit pattern of b 00000000000000000000000000101110 bit pattern of a amp b 00000000000000000000000000001100 Note The bitwise AND amp should not be confused with the logical AND amp amp operator For example 1 amp 4 evaluates to 0 while 1 amp amp 4 evaluates to 1 Bitwise Exclusive OR The bitwise exclusive OR operator compares each bit of its first operand to the corresponding bit of the second operand If both bits are 1 s or both bits are O s the corresponding bit of the result is set to O Otherwise it sets the corresponding result bit to 1 Both operands must have an integral type The
46. an page 104 108 C for AIX User s Guide extern The extern storage class specifier lets you declare objects and functions that several source files can use All object declarations that occur outside a function and that do not contain a storage class specifier declare identifiers with external linkage All function definitions that do not specify a storage class define functions with external linkage An extern variable function definition or declaration also makes the described variable or function usable by the succeeding part of the current source file This declaration does not replace the definition The declaration is used to describe the variable that is externally defined lf a declaration for an identifier already exists at file scope any extern declaration of the same identifier found within a block refers to that same object If no other declaration for the identifier exists at file scope the identifier has external linkage An extern declaration can appear outside a function or at the beginning of a block If the declaration describes a function or appears outside a function and describes an object with external linkage the keyword extern is optional If you do not specify a storage class specifier the function has external linkage Initialization You can initialize any object with the extern storage class specifier at file scope You can initialize an extern object with an initializer that must either e Appear as par
47. can be of any data type Members are overlaid in storage The storage allocated for a union is the storage required for the largest member of the union plus any padding required for the union to end at a natural boundary of its strictest member Declaring a Union p gt union 7 memberi ira ide ntiter identifier Provides a tag name for the union If specified subsequent declarations in the same scope of variables using the union can be made by referring to the tag name If not specified you must place all variable definitions that refer to the union within the declaration of the data type member The list of members provides the data type with a description of the values that can be stored in the union eee decke pa consent ENDES SON deckreter A member that does not represent a bit field can be of any data type and can have the volatile or const qualifier If a colon and a constant expression follow the member declarator the member represents a bit field Bit fields are described in Declaring and Using Bit Fields in Structures page BJ You can reference one of the possible members of a union the same way as referencing a member of a structure For example union char birthday 9 int age float weight people people birthday 0 n assigns n to the first element in the character array birthday a member of the union people A union can represent only one of its members at a ti
48. eight byte representation equivalent to double in C programs Single precision four byte representation float values are automatically converted to double precision before they are used and all results are calculated in double precision Double precision provides greater range and precision than single precision does Double precision values have an approximate range of 10 308 to 10 308 and precision of about 16 decimal digits Single precision values have an approximate range of 10 38 to 10 38 with about 7 decimal digits of precision When results must be converted to single precision rounding operations are used A rounding operation produces the correct single precision value based on the IEEE rounding mode in effect Because explicit rounding operations are required single precision computations are often slower than double precision computations On many other machines the reverse is true single precision operations are faster than Chapter 4 Advanced Compiler Usage 25 double precision operations Code ported from other systems can show different performance on a RISC System 6000 computer See the qfloat rndsngl compiler option for more information about single precision The RISC System 6000 hardware also provides a special set of double precision operations that multiply two numbers and add a third number to the product These combined multiply add maf operations are performed in the same time as a multiply or an add oper
49. file will be included again x Related Reading Option Type Default Value pragma options e Syntax P Purpose Preprocesses the C source files named in the compiler invocation and creates an output preprocessed source file file_name i for each input source file file_name c The P option calls the preprocessor directly as usr vac exe xlCcpp Notes The P option retains all white space including line feed characters with the following exceptions e All comments are reduced to a single space unless C is specified e Line feeds at the end of preprocessing directives are not retained e White space surrounding arguments to function style macros is not retained linedirectives are not issued The P option cannot accept a preprocessed source file file_name ias input Source files with unrecognized filename suffixes are treated and preprocessed as C files and no error message is generated Appendix A Compiler Options 307 In extended mode the preprocessor interprets the backslash character when it is followed by a new line character as line continuation in e macro replacement text e macro arguments e comments that are on the same line as a preprocessor directive Line continuations elsewhere are processed in ANSI mode only The P option is overridden by the E option The P option overrides the c o and qsyntaxonly option The C option may used in conjunction with both the E and P options The defau
50. g option Notes Using qfullpath causes the compiler to preserve the absolute full path name of source files specified with the g option The relative path name of files is preserved when you use qnofullpath qfullpath is useful if the executable file was moved to another directory If you specified qnofullpath the debugger would be unable to find the file Using qfullpath would locate the file successfully Related Reading Option Type Default Value pragma options e Syntax This is a linkage editor Id option Refer to AIX Version 4 Commands Reference for a description of Id command usage and syntax Purpose Tells the linkage editor to create a dynamic library Related Reading 266 C for AIX User s Guide g Option Type Default Value pragma options 7a Syntax g Purpose Generates information used by debugging tools such as the xldb graphical debugger Notes Avoid using this option with O optimization option The information produced may be incomplete or misleading If you specify the g option the inlining option defaults to Q no functions are inlined The default with g is not to include information about unreferenced symbols in the debugging information To include information about both referenced and unreferenced symbols use the qdbxextra option with g To specify that source files used with g are referred to by either their absolute or their relative path name use qfullpath
51. gt 100 0 bLi a i 3 7 x a j b i do not change during execution of the inner loop for i 0 i lt 1000 i for j 0 j lt 1000 j if ali gt 100 0 bLi a i 3 7 xt a j b i The compiler translates the code into a machine language loop that executes as for 1 0 1 lt 1000 i if ali lt 100 00 for j 0 j lt 1000 j bLi aLi 3 7 xt alj blil else for j 0 j lt 1000 j x a j bLi Rearranges the sequence of calculations in an array subscript expression producing more candidates for common expression elimination Replaces less efficient instructions with more efficient ones For example in array subscripting an add instruction replaces a multiply instruction Constants used in an expression are combined and new ones are generated Some implicit conversions between integer and floating point types are done Moves store instructions out of loops Eliminates stores when the value stored is never referred to again For example if two stores to the same location have no intervening load the first store is unnecessary and is removed Eliminates code that cannot be reached or code whose results are not subsequently used Replaces function calls with actual program code Reorders instructions to minimize execution time Uncovers relationships across function calls and eliminates loads stores and computations that cannot be eliminated with more straightforward optimizations
52. ia a a Aa i Am g i aa a ae fms fma fFnms fnma E The following variables record the location of the failing operation the kind of operation and the floating point registers found in a failing instruction Note that the valid registers depend on the instruction type Static unsigned int fpe loc Static char opcode static int frt_reg fra_reg frb_reg frc_reg Mask value to check for floating point exceptions define TST MASK FP_INVALID FP_OVERFLOW FP_UNDERFLOW FP_DIV_ BY ZERO FP_INEXACT Function Prototypes static int find_instr unsigned int trap_loc void enable fp traps int mask void disable fp traps Sample exception handler Customize this code by printing additional debugging information and defining exception results static void fhandler int sig int code struct sigcontext scp fptrap_t fpstat int result_reg 32 C for AIX User s Guide fpstat scp gt sc_jmpbuf jmp context fpscr Check that the trap is of the type used for the flttrap option and that the floating point status and control register indicates that an exception has occurred if int scp gt sc_jmpbuf jmp_context iar FLTTRAPINST fpstat amp TST _MASK This must be a trap caused by an integer division by zero or a subscript out of range fputs SIGTRAP without floating point exception n stderr exit 42 Find the floating point
53. int c size_t count const char file size t line Language Level Extension _debug_ memset is the debug version of memset Like memset it sets the first count bytes of dest to the value c The value of c is converted to an unsigned character _debug_ memset validates the heap after setting the bytes and performs this check only when the target is within a heap _debug_memset makes an implicit call to heap check If debug _memset detects a corrupted heap when it makes a call to heap check debug memset will report the file name file and line number line in a message Note debug memset checks only the current default heap Therefore this debug support will not check all heaps within applications that have multiple user heaps To use _debug memset you must compile with the debug memory qheapdebug compiler option This option maps all memset calls to _debug_memset You do not have to change your source code in order for debug memset to verify the heap Note The qheapdebug option maps all calls to other string functions and all calls to memory management functions including a heap specific version to their debug counterparts To prevent a call from being mapped parenthesize the function name 416 C for AIX Users Guide Return Value _debug_ memset returns a pointer to dest Example This example contains a programming error The invocation of memset that puts B in the buffer specifies the wrong count and stores bytes
54. may be trademarks or service marks of others Copyright IBM Corp 1995 1999 XV XVI C for AIX User s Guide About this Information This information describes the IBM C for AIX licensed program product intended for use with the AIX Version 4 Operating System environment You will find information on using the C for AIX compiler product to compile link and run programs coded in the C language Sections describe how to both write and use compiler options to better optimize programs compile with the C for AIX product Also included is C languge reference information Highlighting Conventions This information uses the following text highlighting conventions Bold Font e Names of operating system commands e Names of compiler options e Names of language keywords e Directory paths Monospaced Font e Information that you should actually type e Examples of code e Examples of text or system messages that you might see displayed on the screen Italic Font e Variables for which you will substitute actual names Related Reading All C for AIX information is available online and can be viewed with an HTML browser You may also want refer to the following publications for additional information IBM Publications e AIX Version 4 System User s Guide Operating System and Devices SC23 2544 Describes the AIX Version 4 Operating System for novice system users It describes how to run commands handle processes files and directories print
55. qcache type I level 1 size 512 line 256 assoc 2 file c Related Reading Option Type Default Value pragma options Syntax 244 C for AIX User s Guide qchars signed qchars unsigned CHARS signed CHARS unsigned Purpose Instructs the compiler to treat all variables of type char as either signed or unsigned Notes You can also specify sign type in your source program using either of the following preprocessor directives pragma options chars sign type pragma chars sign_type where sign_type is either signed or unsigned The _CHAR_SIGNED or CHAR_UNSIGNED macros are defined according to the setting of the qchars option or corresponding preprocessor directives Regardless of the setting of this option the type of char is still considered to be distinct from the types unsigned char and signed char for purposes of type compatibility checking Example To treat all char types as signed when compiling myprogram c enter xlc myprogram c qchars signed Related Reading check Option Type Default Value pragma options Syntax qcheck qcheck suboptions qnocheck CHECK CHECK suboptions NOCHECK Purpose Generates code that performs certain types of runtime checking If a violation is encountered a runtime exception is raised by sending a SIGKILL signal to the process Notes The qcheck option has the following suboptions If you use more than one suboption separate each one with a colon al
56. qheapdebug compiler option This option maps all free calls to debug _free Note The qheapdebug option maps all calls to memory management functions including heap specific versions to their debug counterparts To prevent a call from being mapped parenthesize the function name 408 cC for AIX User s Guide Because _debug_free always checks what heap the memory was allocated from you can use _debug_free to free memory blocks allocated by the regular heap specific or debug versions of the memory management functions However if the memory was not allocated by the memory management functions or was previously freed debug free generates an error message and the program ends Return Value There is no return value Example This example reserves two blocks one of 10 bytes and the other of 20 bytes It then frees the first block and attempts to overwrite the freed storage When _debug_free is called a second time heap check detects the error prints out several messages and stops the program Note You must compile this example with the qheapdebug option to map the free calls to debug free include lt stdlib h gt include lt stdio h gt include lt string h gt int main void char ptrl ptr2 if NULL ptr1 char malloc 10 NULL ptr2 char malloc 20 puts Could not allocate memory block exit EXIT_FAILURE free ptr1 memset ptr1 a 5 overwrites storage that has been fr
57. qinline option to inline functions the compiler attempts to inline the functions you specify Example To compile myprogram c so that no functions are inlined enter xlc myprogram c 0 qnoinline To compile myprogram c so that the compiler attempts to inline functions of fewer than 12 lines enter xlc myprogram c 0 qinline 12 Related Reading ipa Option Type Default Values pragma options e A T A Appendix A Compiler Options 279 Syntax For compile time use qipa qipa object noobject For link time use qipa qipa suboption suboption qnoipa IPA at Compile Time qipa Compile time Description Formats qipa Activates interprocedural analysis with the following qipa suboption default e object qipa object Specifies whether to include standard object code in the object files qipa noobject Specifying the noobject suboption can substantially reduce overall compile time by not generating object code during the first IPA phase If the S compiler option is specified with noobject noobject is ignored If compilation and linking are performed in the same step and neither the S nor any listing option is specified qipa noobject is implied by default If any object file used in linking with qipa was created with the qipa noobject option any file containing an entry point the main program for an executable program or an exported function for a library must be compiled with qipa IPA at Link
58. qprocimported names marks the named functions as imported where names is a list of function identifiers separated by colons The default is not changed The code generated for calls to functions marked as imported might be larger but it is faster than the default code sequence generated for functions marked as unknown If any marked functions are resolved to statically bound objects the generated code may be larger and run more slowly than the default code sequence generated for unknown functions Unknown functions Are resolved to either statically or dynamically bound objects during link editing qprocunknown changes the default to assume that all functions are unknown qprocunknown names marks the named functions as unknown where names is a list of function identifiers separated by colons The default is not changed Conflicts among the procedure marking options are resolved in the following manner Options that list function names The last explicit specification for a particular function name is used Options that change the default This form does not specify a name list The last option specified is the default for functions not explicitly listed in the name list form Example To compile myprogram c along with the archive library oldprogs a so that the functions fun and sun are specified as local moon and stars are specified as imported and venus is specified as unknown enter xlc myprogram c oldprogs a gprolocal fun int
59. struct sl UNION T int C dave 1 By using an existing union tag without a declarator union ul int a int b E struct sl union ul int C dave In both of these examples the members can be accessed as dave a dave b and dave c An anonymous union must be a member of or nested within another anonymous union that is a member of a named structure or union If a union is declared at file scope without a declarator its members are not available to the surrounding scope For example the following union only declares the union tag tom union tom int b float c 3 The variables b and c from this union cannot be used at file scope and the following statements will generate errors Example of union Declaration and Use The following example defines a union data type not named and a union variable named length The member of length can be a long int a float or a double union float meters double centimeters long inches length The following example defines the union type data as containing one member The member can be named charctr whole or real The second statement defines two data type variables input and output Chapter 6 The C Language 105 union data char charctr int whole float real ie union data input output The following statement assigns a character to input input charctr h The following statement assigns a floating point number to member out
60. sun qprocimported moon stars float qprocunknown venus Related Reading proto Option Type Default Value pragma options Syntax qproto qnoproto PROTO NOPROTO Purpose Assumes all functions are prototyped Appendix A Compiler Options 313 Notes This option asserts that procedure call points agree with their declarations even if the procedure has not been prototyped Callers can pass floating point arguments in floating point registers only and not in General Purpose Registers GPRs The compiler assumes that the arguments on procedure calls are the same types as the corresponding parameters of the procedure definition You can obtain warnings for functions that do not have prototypes Example To compile my_c_program c to assume that all functions are prototyped enter xlc my_c_program c qproto Related Reading m LUO On OAE Q Option Type Default Value pragma options tag See betes Syntax Q Q threshold Q names Qtnames Q Purpose Attempts to inline functions instead of generating calls to a function Inlining is performed if possible but depending on which optimizations are performed some functions might not be inlined Notes The Q option is functionally equivalent to the qinlineoption Because inlining does not always improve run time you should test the effects of this option on your code Do not attempt to inline recursive or mutually recursive functions Norm
61. the compiler generates additional code at the beginning of every function that preinitializes the local variables for the function This makes it easier to find uninitialized local variables By default the compiler uses the regular memory management functions calloc malloc new etc and does not preinitialize their local storage Example To compile myprogram c with the debug versions of memory management functions enter xlc qheapdebug myprogram c o testing 270 C for AIX User s Guide Related Reading hsflt Option Type Default Value pragma options Syntax qhsflt qnohsflt HSFLT NOHSFLT Purpose Speeds up calculations by removing range checking on single precision float results and on conversions from floating point to integer qnohsflt specifies that single precision expressions are rounded after expression evaluation and that floating point to integer conversions are to be checked for out of range values Notes This option is obsolete Use qfloat hsflt in your new applications The hsflt option overrides the qrndsngl and qspnans options The qghsflt option is intended for specific applications in which floating point computations have known characteristics Using this option when compiling other application programs can produce incorrect results without warning See i before you use the ghslft option Related Reading Appendix A Compiler Options 271 hssngl Option Type Default Va
62. unary expression An expression that contains one operand union A variable that can hold any one of several data types but only one data type at a time union tag The identifier that names a union data type V variable An object that can take different values at different times W while statement A looping statement that contains the word while followed by an expression in parentheses the condition and a statement the action white space Space characters tab characters form feed characters new line characters and when referring to source code comments Z zero suppression The removal of or substitution of blanks for leading zeros in a number For example 00057 becomes 57 when using zero suppression 498 cC for AIX User s Guide Jb
63. 0 void french enum days weekday switch weekday case Monday printf Le jour de la semaine est Jundi n break case Tuesday printf Le jour de la semaine est mardi n break case Wednesday printf Le jour de la semaine est mercredi n break case Thursday printf Le jour de la semaine est jeudi n break case Friday printf Le jour de la semaine est vendredi n break case Saturday printf Le jour de la semaine est samedi n break case Sunday printf Le jour de la semaine est dimanche n break 84 C for AIX Users Guide default printf C est le mauvais jour n Related Reading void The void data type always represents an empty set of values The only object that can be declared with the type specifier void is a pointer When a function does not return a value you should use void as the type specifier in the function definition and declaration An argument list for a function taking no arguments is void You cannot declare a variable of type void but you can explicitly convert any expression to type void with the resulting expression used only as one of the following e An expression statement e The left operand of a comma expression e The second or third operand in a conditional expression Related Reading Example of a void Declaration On line 7 of the following example the function find_max is declared as having type void Lines 15 through 26 contain the
64. 128 qthreaded D_THREAD_SAFE D__VACPP_MULTI _ x x1C C compiler aliased as x1C_r4 DCE xlC_r4 use DEFLT crt usr vacpp lib crt0 r o 4760 C for AIX Users Guide mert gcrt libraries2 proflibs hdlibs options usr vacpp lib mcrt0_r o usr vacpp lib gcrt0_r o L usr lib threads L usr vacpp 1lib 1C_r 1C ldcelibc_r ldcepthreads Ipthreads lc_r Im usr L usr vacpp 1lib profiled L lib profiled L usr 1lib profiled L usr vac lib IhC_r lhmd_r qansialias qthreaded D VACPP MULTI D THREAD SAFE D AIX32_THREADS 1 D AIX41 D AES SOURCE C compiler with 128 bit long double AIX Threads x1C128 r4 use crt mert gcrt libraries2 proflibs hdlibs options common definition DEFLT cppcomp S DEFLT usr vacpp lib crt0 r o usr vacpp lib mcrt0_r o usr vacpp lib gcrt0_ r o L usr lib threads L usr vacpp lib 1C128_r 1C128 1C_r 1C ldcelibc_r ldcepthreads lpthreads L usr vacpp lib profiled L lib profiled L usr lib profiled L usr vac lib 1hC 1hmd qansialias q1db1128 qthreaded D_THREAD_SAFE D__VACPP_MULTI _ D_AIX32_THREADS 1 D_AIX41 D_AE usr vacpp exe xlCentry ccomp usr vac exe xlcentry code usr vac exe xlCcode cpp usr vac exe x1Ccpp munch usr vacpp exe munch ipa usr vac exe ipa dis usr vac exe dis cppfilt usr vacpp bin ct filt bolt usr vac exe bolt as bin as Id bin d XIC usr vacpp bin x1C cppinc usr vacpp include opti
65. 1991 1999 All Rights Reserved Licensed Materials Property of IBM US Government Users Restricted Rights Use duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp ANSI C compiler UNIX header files Xic use DEFLT crt lib crt0 o mcrt lib mcrt0 o gert lib gcrt0 o libraries lc proflibs L lib profiled L usr lib profiled options qgansialias C compiler extended mode Cc use DEFLT crt lib crt0 o mcrt lib mcrt0 o gcrt lib gcrt0 o libraries lc 474 C for AIX User s Guide x1c128 proflibs options use crt mcrt gcrt libraries proflibs options L lib profiled L usr lib profiled qlanglvl extended qnoro qnoroconst DEFLT lib crt0 o l1ib mcrt0 o lib gcrt0 o c128 1c L lib profiled L usr lib profiled qansialias qldb1128 C compiler extended mode cc128 use crt mcrt gcrt libraries proflibs options DEFLT l1ib crt0 o l1ib mcrt0 o lib gcrt0 o 1c128 lc L lib profiled L usr lib profiled qlanglvl extended qnoro qnoroconst qldb1128 Strict ANSI compiten ANSI headers c89 use crt mcrt gcrt libraries proflibs options C compiler XC use crt mert gcrt libraries2 proflibs hdlibs options DEFLT lib crt0 o l1ib mcert0 o lib gcrt0 o lc L lib profiled L usr lib profiled D_ANSI_C_SOURCE qansialias qnolonglong qstrict_induction DEFLT usr vacpp lib crt0 o usr va
66. 3 Does not inline functions listed by names Separate each name with a colon All other appropriate functions are inlined The option implies Q For example Q salary taxes expenses benefits causes all functions except those named salary taxes expenses or benefits to be inlined if possible A warning message is issued for functions that are not defined in the source file Attempts to inline the functions listed by names and any other appropriate functions Each name must be separated by a colon The option implies Q For example Q food clothes vacation causes all functions named food clothes or vacation to be inlined if possible along with any other functions eligible for inlining A warning message is issued for functions that are not defined in the source file or that are defined but cannot be inlined This suboption overrides any setting of the threshold value You can use a threshold value of zero along with Q names to inline specific functions For example Q 0 followed by Qtsalary taxes benefits causes only the functions named salary taxes or benefits to be inlined if possible and no others The default is to treat inline specifications as a hint to the compiler and depends on other options that you select e If you specify the g option to generate debug information no functions are inlined e f you specify the O option to optimize your program and the Q option to inline
67. Default The default is to assume that all functions whose definition is in the current compilation unit are local proclocal and that all other functions are unknown procunknown If any functions that are marked as local resolve to shared library functions the linkage editor will detect the error and issue warnings such as ld 0711 768 WARNING Object foo o section 1 function printf The branch at address 0x18 is not followed by a recognized no op or TOC reload instruction The unrecognized instruction is 0x83E1004C 312 C for AIX User s Guide An executable file is produced but it will not run The error message indicates that a call to printf in object file foo o caused the problem When you have confirmed that the called routine should be imported from a shared object recompile the source file that caused the warning and explicitly mark printf as imported For example xlc c qprocimported printf foo c Notes Local functions Are statically bound with the functions that call them qproclocal changes the default to assume that all functions are local qproclocal names marks the named functions as local where names is a list of function identifiers separated by colons The default is not changed Smaller faster code is generated for calls to functions marked as local Imported functions Are dynamically bound with a shared portion of a library qprocimported changes the default to assume that all functions are imported
68. If you specify a storage class specifier you can omit the type specifier If you omit the type specifier all variables in that declaration receive type int Initialization You cannot initialize a variable declared in a block scope data declaration that has the extern storage class specifier The types of variables you can initialize and the values that uninitialized variables receive vary for that storage class specifier See 9 for details on the different storage classes Storage The duration and type of storage varies for each storage class specifier 62 C for AIX User s Guide Declarations with the auto or register storage class specifier result in automatic storage duration Declarations with the extern or static storage class specifier result in static storage duration Related Reading File Scope Data Declarations A file scope data declaration appears outside any function definition It describes a variable and makes that variable accessible to all functions that are in the same file and whose definitions appear after the declaration A file scope data definition is a data declaration at file scope that also causes storage to be allocated for that variable All objects whose identifiers are declared at file scope have static storage duration Use a file scope data declaration to declare variables that you want to have external linkage The only storage class specifiers you can put in a file scope data declaration a
69. K k K K k K k K ERK k K KEKE KK k K k K k K K K Kk Kk Kk K Kk Kk Kk k kk kk kkk kk kk kkk kk kk Related Reading _debug_strset Set Characters in String Format include lt string h gt char debug strset char string size t cC const char file size t line Language Level Extension 4260 for AIX Users Guide _debug_strset is the debug version of sirset Like sirset it sets all characters of string except the ending null character 0 to c converted to a char _debug_strset validates the heap after setting all characters of string and performs this check only when the target is within a heap _debug_strset makes an implicit call to heap _check If debug_strset detects a corrupted heap when it makes a call to heap check debug _strset will report the file name file and line number line in a message Note debug_strset checks only the current default heap Therefore this debug support will not check all heaps within applications that have multiple user heaps To use _debug_strset you must compile with the debug memory qheapdebug compiler option This option maps all strset calls to _debug_strset You do not have to change your source code in order for _debug_strset to verify the heap Note The qheapdebug option maps all calls to other string functions and all calls to memory management functions including a heap specific version to their debug counterparts To prevent a call from being mapped parenthesize the
70. ROLL SALMON ROLL TUNA SQUID UNI enum sushi first_order UNI Appendix A Compiler Options 257 The enumerations test_enum and test_order both occupy 4 bytes of storage and are of type int The variable u_char_e_var defined in small_enum h occupies 1 byte of storage and is represented by an unsigned char data type 2 If the following C fragment is compiled with the enum small option enum e tag a b c e var the range of enum constants is 0 through 2 This range falls within all of the ranges described in the table above Based on priority the compiler uses predefined type unsigned char 3 If the following C code fragment is compiled with the enum small option enum e tag a 129 b c e var the range of enum constants is 129 through 127 This range only falls within the ranges of short signed short and int signed int Because short signed short has a higher priority it will be used to represent the enum 4 If you compile a file myprogram c using the command xlc myprogram c qenum smal assuming file myprogram c does not contain pragma options int statements all enum variables within your source file will occupy the minimum amount of storage 5 If you compile a file yourfile c that contains the following lines enum testing ONE TWO THREE enum testing test enum pragma options enum smal enum sushi CALIF ROLL SALMON ROLL TUNA SQUID UNI enum sushi first_order UNI pragma options enum i
71. Searches the directory where your current source file resides The current source file is the one that contains the directive include file_name If you specify the option ldirectory the compiler searches for file_name in directory lf more than one directory is specified the compiler searches the directories in the order that they appear on the command line Searches the directory usr include Notes 1 file_name is the path name of the file to be included When you specify a full path name the two versions of the include directive have the same effect because the location of the file to be included is completely specified With a relative path name the directory search sequence is determined by whether you use the lt gt or the characters 2 The only difference between the two versions of the include directive is that the user include version first searches in the directory where your current source file resides Typically standard header files are included using the lt gt system include version and header files that you create are included using the user include version 3 You can change the search order by specifying the qstdinc and qidirfirst options along with the Idirectory option Use the qnostdinc option to search only the directories specified with the ldirectory option and the current source file directory if applicable The usr include directory is not searched
72. Technique Value Numbering Involves constant propagation expression elimination and folding of several instructions into a single instruction Branch Optimizations Rearranges the program code to minimize branching logic and to combine physically separate blocks of code Copyright IBM Corp 1995 1999 23 Common Subexpression Elimination Code Motion Invariant IF Code Floating Unswitching Reassociation Strength Reduction Constant Propagation Store Motion Dead Store Elimination Dead Code Elimination Inlining Q option Instruction Scheduling Interprocedural Analysis qipa option 24 C for AIX User s Guide In common expressions the same value is recalculated in a subsequent expression The duplicate expression can be eliminated by using the previous value This step is done even for intermediate expressions within expressions For example if your program contains the following statements a Fa f ctdte the common expression c d is saved from its first evaluation and is used in the subsequent statement to determine the value of f If variables used in a computation within a loop are not altered within the loop the calculation can be performed outside of the loop and the results used within the loop Removes invariant branching code from loops to make more opportunity for other optimizations For example in the following code segment the condition test and the conditional assignment if ali
73. The declaration for a data object can include the following components e Qualifier and declarator e Storage class e Initializer e Type specifier The following table shows examples of declarations and definitions The identifiers declared in the first column do not allocate storage they refer to a corresponding definition In the case of a function the corresponding definition is the code or body of the function The identifiers declared in the second column allocate storage they are both declarations and definitions Declarations Declarations and Definitions extern double pi double pi 3 14159265 float square float x float square float x return x x Chapter 6 The C Language 61 Declarations Declarations and Definitions struct payroll struct payroll char name float salary employee Related Reading Block Scope Data Declarations In C a block scope data declaration can only be put at the beginning of a block It describes a variable and makes that variable accessible to the current block All block scope declarations that do not have the extern storage class specifier are definitions and allocate storage for that object You can declare a data object with block scope with any one of the following storage class specifiers e auto e extern e register e static e typedef If you do not specify a storage class specifier in a block scope data declaration the default storage class specifier auto is used
74. Time qipa Link time Description Formats qnoipa Deactivates interprocedural analysis qipa Activates interprocedural analysis with the following qipa suboption defaults e inline auto e level 1 e missingzunknown e partition medium suboption Suboptions can take any of the forms shown below Separate multiple suboptions with commas exits name name Specifies names of functions which represent program exits Program exits are calls which can never return and can never call any procedure which has been compiled with IPA pass 1 280 C for AIX User s Guide inline suboption Same as specifying the qinline compiler option with suboption being any valid qinline suboption inline auto Enables automatic inlining only The compiler still accepts user specified functions as candidates for inlining inline noauto Disables automatic inlining only The compiler still accepts user specified functions as candidates for inlining inline name name Specifies a comma separated list of functions to try to inline where functions are identified by name noinline name name Specifies a comma separated list of functions that must not be inlined where functions are identified by name inline limit num Changes the size limits that the Q option uses to determine how much inline expansion to perform This established limit is the size below which the calling procedure must remain number is the optimizer s approximation of the number
75. To avoid the ambiguity and have x evaluated first replace the preceding sequence of statements with the following int X y x l y Xtt tester y x The value of the second parameter in the following example is unpredictable int xX x l tester x x The following sequence of statements avoids this ambiguous function call by having x evaluated first Int X y x l y Xt tester y x Related Reading C Language Levels To help you avoid conflicts between the different C language definitions in existance the C for AIX compiler supports several levels of the C language Available language levels and their descriptions are Level Description ansi Conforms to the American National Standards Institute ANSI C standard classic Conforms closely to the K amp R level preprocessor enabling the compilation of many non ANSI programs extended High compatibility with RT C source code extended level C is defined as ansi level C extended for compatibility with the RT compiler RT compatibility conflicts with the ANSI C standard under certain conditions saal2 Systems Application Architecture SAA CPI C Level 2 saal2 level C conforms to SAA C with some deviations saa The highest level SAA C definition available This is currently SAA Level 2 C Note saal2 and saa C language levels are options of the C for AIX compiler and are not part of the SAA Common Programming Interface 78 C for AIX Users G
76. You can also use the qlinedebug option to produce abbreviated debugging information in a smaller object size Some symbols which are clearly referenced or set in the source code may be optimized away by IPA and may be lost to debug nm or dump outputs Using IPA together with the g compiler will usually result in non steppable output Example To compile myprogram c to produce an executable programtesting so you can debug it enter xlc myprogram c o testing g To compile myprogram c to produce an executable program testing_all containing additional information about unreferenced symbols so you can debug it enter xlc myprogram c o testing all g qdbxextra Related Reading genpcomp Option Type Default Value pragma options aoptin nogenpcome Appendix A Compiler Options 267 Syntax qgenpcomp qgenpcomp directory qnogenpcomp Purpose Generates a precompiled version of any header file for which the original source file is used This may help improve compile time when you use the qusepcomp option Notes qgenpcomp Generates a precompiled header file called csetc pch and saves it to the current directory qgenpcomp directory Generates a precompiled header file e If directory is the name of an existing directory the precompiled header file is named csetc pch and saved to that named directory e lf a directory with the name directory does not exist the precompiled header file is named directory and is
77. _ raj exoressign A return statement in a function is optional The compiler issues a warning if a return statement is not found in a function declared with a return type If the end of a function is reached without encountering a return statement control is passed to the caller as if a return statement without an expression were encountered A function can contain multiple return statements Value of a return Expression and Function Value If an expression is present on a return statement the value of the expression is returned to the caller If the data type of the expression is different from the function return type conversion of the return value takes place as if the value of the expression were assigned to an object with the same function return type If an expression is not present on a return statement the value of the return statement is undefined If an expression is not given on a return statement in a function declared with a nonvoid return type a warning message Is issued and the result of calling the function is unpredictable You cannot use a return statement with an expression when the function is declared as returning type void Related Reading Examples Using the return Statement The following are examples of return statements return Returns no value x return result Returns the value of result return 1 Returns the value 1 x return x x Returns the value of x x The following fu
78. accept only one schedule clauses e The value of n chunk size must be the same for all threads of a parallel region 392 C for AIX User s Guide Related Reading pragma omp parallel for Preprocessor Directive The omp parallel for directive effectively combines the omp parallel and omp for directives This directive lets you define a parallel region containing a single omp for directive in one step Syntax pragma omp parallel for clause clause lt for_loop gt All clauses and restrictions described in the omp parallel and omp for directives apply to the omp parallel for directive Related Reading pragma omp sections Preprocessor Directive The omp sections directive distributes work among threads bound to a defined parallel region Syntax pragma omp sections clause clause pragma omp section statement block pragma omp section statement block where clause is any of the following private list Declares the scope of the data variables in ist to be private to each thread Data variables in list are separated by commas firstprivate list Declares the scope of the data variables in ist to be private to each thread Each new private object is initialized as if there was an implied declaration within the statement block Data variables in list are separated by commas lastprivate list Declares the scope of the data variables in ist to be private to each thread The final value of each v
79. add values of operands having different data types both values are first converted to the same type For example when a short int value and an int value are added together the short int value is converted to the int type Implicit type Conversions can occur when e A value is prepared for an arithmetic or logical operation e An assignment is made to an lvalue that has a different type than the assigned value e A prototyped function is provided a value that has a different type than the parameter 74 C for AIX Users Guide e The value specified in the return statement of a function has a different type from the defined return type for the function You can perform explicit type conversions using the cast operator or the function style cast For more information on explicit type conversions see Type Casting page 29 Signed Integer Conversions The compiler converts a signed integer to a shorter integer by truncating the high order bits and converting the variable to a longer signed integer by sign extension Conversion of signed integers to floating point values takes place without loss of information except when an int or long int value is converted to a float in which case some precision may be lost When a signed integer is converted to an unsigned integer the signed integer is converted to the size of the unsigned integer and the result is interpreted as an unsigned value Unsigned Integer Conversions An unsigned integer is
80. and _udestroy work slightly differently Calling _uheapmin for a fixed size heap has no effect but does not cause an error uheapmin simply returns 0 Calling _udestroy for a fixed size heap marks the heap as destroyed so no further operations can be performed on it but returns no memory It is up to you to return the heap s memory to the system Related Reading Example of Creating and Using a User Heap The program below shows how you might create and use a heap Assuming that the program file is called t c compile it with the following command usr vac bin cc qheapdebug t c lhu include lt stdlib h gt include lt stdio h gt include lt umalloc h gt Static void get _fn Heap t usrheap size_t length int clean void p Round up to the next chunk size xlength length 65536 65536 65536 Clean BLOCK CLEAN p calloc length 1 return p Static void release fn Heap_t usrheap void p size t size free p returns int main void void initial block long rc Heap _t myheap char ptr int initial sz Get initial area to start heap 190 C for AIX User s Guide Thitial sz 65536 initial block malloc initial sz if initial_ block NULL return 1 create a user heap myheap _ucreate initial block initial_sz _BLOCK CLEAN _HEAP_REGULAR get_fn release fn if myheap NULL return 2 allocate from user heap and cause it to grow p
81. ansi mode an attempt to assign pointers of different types to each other produces an error message extended mode accepts the assignment e enum declarations containing a trailing extra comma Accepted in extended mode but not in ansi mode e No definition of static function ansi mode requires a function declared static to be defined in the same file as the declaration In extended mode a function that is declared static but is not defined in the same file as the declaration is implicitly redeclared extern An informational message is produced e sizeof operator on bit fields Allowed by extended but not by ansi e String literals 162 C for AIX Users Guide Both ansi and extended modes give you the choice of making string literals either modifiable or unmodifiable but the defaults are different The default is modifiable for extended and unmodifiable for ansi e Ref def model The ANSI ISO C standard defines a relaxed strict and initialization ref def model for objects with external linkage extended mode supports the relaxed model whereas ansi mode supports a combination of the strict and initialization models e unsigned char and unsigned short bit fields Allowed in extended mode but not in ansi mode In extended mode an error message is issued but compilation continues Both unsigned char and unsigned short are changed to unsigned int For bit fields unsigned char and unsigned short are changed to unsigned int e lo
82. are performed The result has the type produced by the conversions on the operands and is not an Ivalue When the left operand is a pointer and the right operand has an integral type the compiler converts the value of the right to an address offset The result is a pointer of the same type as the pointer operand If both operands are pointers to the same type the compiler converts the result to an integral type that represents the number of objects separating the two addresses Behavior is undefined if the pointers do not refer to objects in the same array Chapter 6 The C Language 125 Bitwise Shifts The bitwise shift operators move the bit values of a binary object The left operand specifies the value to be shifted The right operand specifies the number of positions that the bits in the value are to be shifted The result is not an lvalue Both operands have the same precedence and are left to right associative Operator Usage lt lt Indicates the bits are to be shifted to the left gt gt Indicates the bits are to be shifted to the right Each operand must have an integral type The compiler performs integral promotions on the operands Then the right operand is converted to type int The result has the same type as the left operand after the arithmetic conversions The right operand should not have a negative value or a value that is greater than or equal to the width in bits of the expression being shifted The result
83. are passed in FPR1 FPR13 In all cases parameters beyond the first 8 words of the list are also stored in the space reserved for them 4 lf thecalled procedure intends to treat the parameter list as a contiguous piece of storage for example if the address of a parameter is taken in C the parameter registers are stored in the space reserved for them in the stack 5 A register image is stored on the stack 6 The argument area P Pa must be large enough to hold the largest parameter list Related Reading Interlanguage Calls Pointers to Functions A function pointer is a data type whose values range over function addresses Variables of this type appear in several programming languages such as C and Fortran In Fortran a dummy argument that appears in an EXTERNAL statement is a function pointer Function pointers are supported in contexts such as the target of a call statement or an actual argument of such a statement A function pointer is a fullword quantity that is the address of a function descriptor The function descriptor is a 3 word object The first word contains the address of the entry point of the procedure the second has the address of the TOC of the module in which the procedure is bound and the third is the environment pointer for languages such as Pascal There is only one function descriptor per entry point It is bound into the same module as the function it identifies if the function is external The descripto
84. as volatile Declaring and Using Bit Fields in StructuresA structure can contain bit fields that allow you to access individual bits You can use bit fields for data that requires just a few bits of storage A bit field declaration contains a type specifier followed by an optional declarator a colon a constant expression and a semicolon Pr npe speaher En contant eoressian EGSA The constant expression specifies how many bits the field reserves Bit fields with a length of O must be unnamed Unnamed bit fields cannot be referenced or initialized A zero width bit field causes the next field to be aligned on the next container boundary where the container is the same size as the underlying type as the bit field The maximum bit field length is implementation dependent The maximum bit field length for the C for AIX compiler is 32 bits 4 bytes or 1 word Chapter 6 The C Language 97 For portability do not use bit fields greater than 32 bits in size The following restrictions apply to bit fields You cannot e Define an array of bit fields e Take the address of a bit field e Have a pointer to a bit field In C you can declare a bit field as type int signed int or unsigned int Bit fields of the type int are equivalent to those of type unsigned int The default integer type for a bit field is unsigned Use the bitfields signed option to change this default In extended mode C bit fields can be any integral type
85. associated with the omp sections directive When program execution reaches a omp sections directive program segments defined by the following omp section directive are distributed for parallel execution among available threads A barrier is implicitly defined at the end of the larger program region associated with the omp sections directive unless the nowait clause is specified Related Reading pragma omp parallel sections Preprocessor Directive The omp parallel sections directive effectively combines the omp parallel and omp sections directives This directive lets you define a parallel region containing a single omp sections directive in one step Syntax pragma omp parallel sections clause clause pragma omp section statement block pragma omp section statement block E All clauses and restrictions described in the omp parallel and omp sections directives apply to the omp parallel sections directive 394 C for AIX User s Guide Related Reading pragma omp single Preprocessor Directive The omp single directive identifies a section of code that must be run by a single available thread Syntax pragma omp single clause clause statement_block where clause is any of the following private list Declares the scope of the data variables in ist to be private to each thread Data variables in list are separated by commas firstprivate list Declares the scope of the data variables in ist t
86. based applications continue to run in 1 1 mode Inthe m n model all user threads are mapped to a pool of kernel threads and all user threads run on a pool of virtual processors One user thread may be bound to a specific virtual processor like 1 1 with remaining threads using the remaining virtual processors in the pool This is the newest and most complex model It is the default for XPG 5 Previously AIX 4 3 0 XPG 5 based applications ran in 1 1 mode The same application now runs in m n mode in AIX 4 3 1 The application should continue to function correctly however the performance of the application is likely to change Copyright IBM Corp 1995 1999 345 The AIXTHREAD_SCOPE environment variable resets the disposition of the default attribute This can be used to change the scheduling policy from m n to 1 1 or vice versa Settings for this environment variable are AIXTHREAD_SCOPE sched_policy where sched_policy is one of process based scheduling m n S system based scheduling 1 1 The AIXTHREAD_ SCOPE environment variable can also be used to overcome problems associated with the m n based scheduling APAR IX76628 is available to fix these problems We recommend setting the environment variable to S if your threaded application encounters problems Related Reading 346 C for AIX User s Guide Appendix D Preprocessor Directives and Related Information List of Standard Preprocessor Directives This
87. be inlined if possible A warning message is issued for functions that are not defined in the source file 278 C for AIX User s Guide qinlinetnames Attempts to inline the functions listed by names and any other appropriate functions Each name must be separated by a colon The option implies qinline For example qinline food clothes vacation causes all functions named food clothes or vacation to be inlined if possible along with any other functions eligible for inlining A warning message is issued for functions that are not defined in the source file or that are defined but cannot be inlined This suboption overrides any setting of the threshold value You can use a threshold value of zero along with qinline names to inline specific functions For example qinline 0 followed by qinlinetsalary taxes benefits causes only the functions named salary taxes or benefits to be inlined if possible and no others qinline limit Specifies the maximum size in bytes of generated code to which a function can grow due to inlining This limit does not affect the inlining of user specified functions qinline Is the same as Q Default The default is to treat inline specifications as a hint to the compiler and the result depends on other options that you select e If you specify the g option to generate debug information no functions are inlined e If you specify the O option to optimize your program and the
88. called a trigraph A sequence of two characters is called a digraph but will be accepted by the compiler only if the qdigraph compiler option is in effect Digraph or trigraph character sequences appearing in character or string literals are not replaced during the preprocessor stage Digraph and trigraph sequences available to you are 160 C for AIX User s Guide aae re es E backslash substitute for preprocessor macro concatenation operator Escape Sequences for Non Printable Characters Related Reading Reserved Keywords Keywords are identifiers reserved by the C language for special use You can use them for preprocessor macro names but that is however considered poor programming style Only the exact character case and spelling of keywords is reserved For example auto is reserved but AUTO is not Keywords reserved by the C programming language are auto break case char const continue default do double else enum extern float for goto if int long register return Short Signed sizeof Static struct Switch typedef union Chapter 6 The C Language 161 unsigned void volatile while Identifier names should not start with an underscore _ followed by an uppercase letter and should not contain two underscores __ anywhere The compiler and library use identifiers beginning with single and double underscores for their own purposes Differences Between C Language Levels Conflicts Between extended C
89. command line syntax of the compiler option The first line under the Syntax heading specifies the command line or configuration file method of specification The second line if one appears is the pragma options keyword for use in your source file e The default setting of the option if you do not specify the option on the command line in the configuration file or in a pragma directive within your program e The purpose of the option and additional information about its behavior Uppercase letters in the option suboption or pragma options keyword syntax represent its valid abbreviation For example both of the following are acceptable specifications of the LANGIvI option in a source file pragma options lang ansi pragma options langlvl ansi Options that appear entirely in lowercase must be entered in full Related Reading Resolving Conflicting Compiler Options In general if more than one variation of the same option is specified with the exception of xref and attr the compiler uses the setting of the last one specified Compiler options specified on the command line must appear in the order you want the compiler to process them lf a command line flag is valid for more than one compiler program for example B W or I applied to the compiler linkage editor and assembler program names you must specify it in cppopt codeopt inlineopt Idopt or asopt in the configuration file The command line flags must appear in t
90. completed and produces as output an object file file_name o for each file_name c input source file The linkage editor is not invoked You can link edit the object files later using the invocation command specifying the object files without the c option Notes 1 Any object files produced from an earlier compilation are deleted as part of the compilation process even if new object files are not produced 2 By default the invocation command calls both the compiler and the linkage editor It passes linkage editor options to the linkage editor Consequently the invocation commands also accept all linkage editor options Related Reading Invoking the Linkage Editor The linkage editor link edits all of the specified object files to create one executable file Invoking the compiler with one of the invocation commands automatically calls the linkage editor unless you specify one of the following compiler options E P c or Input Files Object files library files and unstripped executable files serve as input to the linkage editor Object Files Object files must have a o suffix for example year o Library Files Static library file names have a a suffix for example libold a Dynamic library file names have a so suffix for example libold so Library files are created by combining one or more files into a single archive file with the AIX ar command For a description of the ar command refer to the AlX Version 4 Commands
91. contains a condition the first expression an expression to be evaluated if the condition has a nonzero value the second expression and an expression to be evaluated if the condition has the value zero the third expression const A keyword that allows you to define a variable whose value does not change constant A data item with a value that does not change during program execution constant expression An expression having a value that can be determined during compilation and that does not change during program execution 490 C for AIX User s Guide control statement A C language statement that changes the normal path of execution conversion A change in the type of a value For example when you add values having different data types the compiler converts both values to the same type before adding them D data definition A program statement that describes the features of specifies relationships of or establishes the context of data A data definition can also provide an initial value Definitions appear outside a function for example at file scope or within a block statement data object Anything that exists in storage and on which operations can be performed such as files programs or arrays data type A category that specifies the interpretation of a data object such as its mathematical qualities and internal representation DBCS See kad debug To detect locate and correct errors in a program decimal co
92. converted to a shorter unsigned or signed integer by truncating the high order bits An unsigned integer is converted to a longer unsigned or signed integer by zero extending Zero extending pads the leftmost bits of the longer integer with binary zeros When an unsigned integer is converted to a signed integer of the same size no change in the bit pattern occurs However the value changes if the sign bit is set Floating Point Conversions A float value converted to a double undergoes no change in value A double converted to a float is represented exactly if possible If the compiler cannot exactly represent the double value as a float the value loses precision If the value is too large to fit into a float the result is undefined When a floating point value is converted to an integer value the decimal fraction portion of the floating point value is discarded in the conversion If the result is too large for the given integer type the result of the conversion is undefined Pointer Conversions Pointer conversions are performed when pointers are used including pointer assignment initialization and comparison A constant expression that evaluates to zero can be converted to a pointer This pointer will be a null pointer pointer with a zero value and is guaranteed not to point to any object Any pointer to an object that is not a const or volatile object can be converted to a void You can also convert any pointer to a function t
93. copying the string to the target location and performs this check only when the target is within a heap _debug_strcpy makes an implicit call to heap check If _debug_strcpy detects a corrupted heap when it makes a call to heap check debug _strcpy will report the file name file and line number line in a message Note debug_strcpy checks only the current default heap Therefore this debug support will not check all heaps within applications that have multiple user heaps To use _debug_strcpy you must compile with the debug memory qheapdebug compiler option This option maps all strcpy calls to debug_strcpy You do not have to change your source code in order for _debug_strcpy to verify the heap Note The qheapdebug option maps all calls to other string functions and all calls to memory management functions including a heap specific version to their debug counterparts To prevent a call from being mapped parenthesize the function name Return Value _debug_strcpy returns a pointer to the copied string string Example This example contains a programming error The source string is too long for the destination buffer and the strcpy operation damages the heap include lt stdlib h gt include lt stdio h gt include lt string h gt define SIZE 10 int main void char source 1234567890123456789 char destination char return_string destination char malloc SIZE strcpy destination abcdefg pri
94. directories have been searched the directories on the standard list for include files are searched The directories on the standard list differ for the two versions of the include directive See j ive Path Names on paqe 3 for more information about searching directories 2 2 C for AIX User s Guide The Idirectory option can be specified more than once on the command line If you specify more than one option directories are searched in the order that they appear on the command line If you specify a full absolute path name on the include directive this option has no effect Example To compile myprogram c and search usr tmp and then oldstuff history for included files enter xlc myprogram c I usr tmp I oldstuff history Related Reading idirfirst Option Type Default Value pragma options Syntax qidirfirst qnoidirfirst IDIRFIRST NOIDIRFIRST Purpose Specifies the search order for files included with the include file_name directive Notes Use qidirfirst with the Idirectory option The normal search order for files included with the include file_name directive without the idirfirst option is 1 Search the directory where the current source file resides 2 Search the directory or directories specified with the Idirectory option 3 Search the standard include directory usr include With qidirfirst the directories specified with the Idirectory option are searched before th
95. eeu eee eeeeeeoeeuaeaecseeueweetizeees Ge amp amp 2 ww 2 US Pascal a 2 k a ke ee eee De ee ee ke ee he ke me ot ee ewe HF OOS Odi pdi2 2 eek se wwe ee ePee EER Ee EEE HBO SD SS eG ee OUD Dds oa tease ew eeae ease eeeeaetien etgateae ee be ee 2 2a ONSINNIG s 2 sos os e e ea we oe oo mt ee he ee ee Fe eo oe et me we Ode proclocal procimported procunknown a ee eee ee 812 OO se he ee eee SG ee ee ee ee he ee ee ee ee SF oe eA ew lO Ga e e r e e eh eee eeeaee een a a a a ese 2 oe ale Caa a a a a n a a a a a a a a a a a eos a a a O MASNO 4 s he we hee eh ee ee Oo o o ee FR e ee ee a ee a dO OO eb ae ee ee eee eee ee ee Oe ee eee ke Pe ee a ee eS Od OCONSl 6 nes eee he ee ee ke ee ee ee ee ee he ee ee eo Ode hae ae ee ee te Se eee eee ke ee eh eke eae ee ee ee ee SB OS Oa stcanetsceeeeBPeBaweneeheeeietiieteiouwveuzeeaeeze amp amp amp 2 OID SHOWING s x ss s eb oa seeeneeeu eevee tonn ee oe we ee OAD SMO ueiaiseae echt reeecwehe GB aoueeueeaeeeeeeeeeuae amp r0c0 SOUICG 2 e Rew te ee ee oie oe ee He a he se ew ee ee oe amp SF uw ee Sill 5 Bee he eee eee eee eee eee ee ee ee ee Oe we eB eS SOMONSs amp fe amp oe we ee te oe tb ee we ee oe ee oe ws ee et ee ee eH He OES Soiled 4a aes ee eke bw ee te ee ee oe ee ee ee ee ee Se StalSyM s s s rs eee oo eek ee eee ee eo eee ko ee oe ew ee Se a O24 SONG e a s k A p a Foe stew eee eae BeBe se eae se ee we ee g p 920 Silla s16e ee
96. evaluated Related Reading Examples of Operator Precedence and Associativity The parentheses in the following expressions explicitly show how the compiler groups operands and operators If the parentheses did not appear in these expressions the operands and operators are grouped in the same manner as indicated by the parentheses total 4 5 3 total 8 5 10 3 total 10 5 3 Because the order of grouping operands with operators that are both associative and commutative is not specified the compiler can group the operands and operators in the expression total price prov_tax city tax in the following ways as indicated by the parentheses 68 C for AIX User s Guide total price prov_tax city tax total price prov_tax city tax total price prov_tax city tax If the values in this expression are integers the grouping of operands and operators does not affect the result Different groupings of floating point operators however may give different results because intermediate values are rounded In certain expressions the grouping of operands and operators can affect the result For example in the following expression each of the three function calls might modify the same global variables a b c d This expression might give different results depending on the order in which the functions are called If the expression contains operators that are both assoc
97. following output price 1 41 price 1 50 price 3 75 price 5 00 price 0 86 total 1 48 total 1 57 total 3 94 total 5 25 total 0 90 The following program defines the multidimensional array salary _tbl A for loop prints the values of salary tbl x xx Example of a multidimensional array include lt stdio h gt define ROW SIZE 3 define COLUMN SIZE 5 int main void static int salary _tbl ROW SIZE COLUMN SIZE 500 550 600 650 700 P 600 670 740 810 880 fs 740 840 940 1040 1140 E int grade step for grade 0 grade lt ROW_SIZE grade for step 0 step lt COLUMN SIZE step printf salary_tbl d d d n grade step salary_tbl grade step return 0 This program produces the following output salary tb1 0 0 500 salary tb1 0 1 550 salary _tb1 0 2 600 salary_tb1 0 3 650 salary tb1 0 4 700 salary _tb1 1 0 600 salary tb1 1 1 670 salary _tb1 1 2 740 salary tb1 1 3 810 salary_tb1 1 4 880 salary tb1 2 0 740 salary tb1 2 1 840 salary tb1 2 2 940 salary tb1 2 3 1040 salary tb1 2 4 1140 Related Reading Chapter 6 The C Language 89 Pointers A pointer type variable holds the address of a data object or function A pointer can refer to an object of any one data type but cannot point to a bit field or to an object having the register storage class spec
98. function name Return Value _debug_strset returns a pointer to the altered string There is no error return value Example This example contains a programming error The string str was created without a null terminator and strset propagates the letter k until it finds what it thinks is the null terminator include lt stdlib h gt include lt stdio h gt include lt string h gt int main void char str str char malloc 10 strnset str x 5 strset strt 5 k printf This is the string after strset s n str return 0 BRK RR k k k k RE RRR KEKE RK ERR ERR K K k R KER KERR ERE ERR RRR KEKE KER kkk ERK RRR The output should be End of allocated object 0x00073c80 was overwritten at 0x00073c8a The first eight bytes of the memory block in hex are 78787878786B6B6B This memory block was re allocated at line number 9 in strset c Heap state was valid at line 11 of strset c Memory error detected at line 12 of strnset c KKK KKK KKK ERK KERR kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkx Appendix F C for AIX Debug Functions 427 Related Reading _debug_ucalloc Reserve and Initialize Memory from User Heap Format include lt umalloc h gt void debug ucalloc Heap t heap size_t num size t size const char file size t line Language Level Extension _debug_ucalloc is the debug version of _ucalloc Like _ucalloc it allocates memory from the heap you specify fo
99. functions the compiler attempts to inline the functions you specify Example To compile the program myprogram c so that no functions are inlined enter xlc myprogram c 0 Q Appendix A Compiler Options 315 To compile the program my_c_program c so that the compiler attempts to inline functions of fewer than 12 lines enter xlc my_c_program c 0 Q 12 Related Reading Option Type Default Value pragma options e Syntax y Purpose Produces a relocatable object This permits the output file to be produced even though it contains unresolved symbols Notes A file produced with this flag is expected to be used as a file parameter in another call to xle Example To compile myprogram c and myprog2 c into a single object file mytest o enter xlc myprogram c myprog2 c r o mytest o Related Reading rndsngl Option Type Default Value pragma options Syntax qrndsngl qnorndsngl RNDSNGL NORNDSNGL Purpose Specifies that the results of each single precision float operation is to be rounded to single precision qnorndsngl specifies that rounding to single precision happens only after full expressions have been evaluated Notes This option is obsolete Use qfloat rndsngl in your new applications 316 C for AIX User s Guide The ghsflt option overrides the qrndsngl options The qrndsngl option is intended for specific applications in which floating point computations have known charact
100. has been subtracted from the exponent Set the result of any overflow to zero Scp gt sc_jmpbuf jmp_context fpr frt_reg 0 0 if fpstat amp TRP_UNDERFLOW FP_UNDERFLOW TRP_UNDERFLOW FP_UNDERFLOW fprintf stderr FP underflow operation s location x n opcode fpe loc x Note that the result register in an underflow contains a correctly rounded normalized number but 1536 has been added to the exponent Chapter 4 Advanced Compiler Usage 33 Set the result of any underflow to zero i scp gt sc_jmpbuf jmp_context fpr frt_reg 0 0 if fpstat amp TRP DIV BY ZERO FP DIV BY ZERO TRP_DIV_BY ZERO FP_DIV BY ZERO fprintf stderr FP division by zero operation s location x n opcode fpe loc Print the source operands for the division the divide instruction uses FRA and FRB Note that the result register has not been modified by the divide fprintf stderr Division source operands f f n scp gt sc_jmpbuf jmp context fpr fra_reg scp gt sc_jmpbuf jmp_ context fpr frb_ reg Set the result of any division by zero to zero Scp gt sc_jmpbuf jmp context fpr frt_reg 0 0 if fpstat amp TRP_INEXACT FP_INEXACT TRP_INEXACT FP_INEXACT fprintf stderr FP inexact operation s location x n opcode fpe loc No action just ignore this Reset the exception bits because they are sticky Scp gt sc
101. having values that may be changed in ways unknown to your program such as the system clock Portions of an expression that reference volatile objects are not to be changed or removed Note These type qualifiers are only meaningful in expressions that are lvalues For a volatile or const pointer you must put the keyword between the and the identifier For example int volatile x x is a volatile pointer to an int int const y amp z y is a const pointer to the int variable z For a pointer to a volatile or const data object the type specifier qualifier and storage class specifier can be in any order For example volatile int x1 xl is a pointer to a volatile int int volatile x2 x2 is a pointer to a volatile int const int yl yl is a pointer to a const int int const y2 y2 is a pointer to a const int In the following example the pointer to y is a constant You can change the value that y points to but you cannot change the value of y int const y In the following example the value that y points to is a constant integer and cannot be changed However you can change the value of y const int y For other types of volatile and const variables the position of the keyword within the definition or declaration is less important For example volatile struct omega int limit char code groups provides the same storage as struct omega int limit char code
102. if result is negative or too large the result is undefined Truncate if result is negative or too large the result is undefined Truncate if result is negative or too large the result is undefined To signed char signed short Represent as float if the int cannot be represented exactly some loss of precision may occur signed long Represent as float if the long cannot be represented exactly some loss of precision may occur signed long long Represent as float if the long long cannot be represented exactly some loss of precision may occur unsigned char unsigned short unsigned int Represent as float if the int cannot be represented exactly some loss of precision may occur unsigned long Represent as float if the long cannot be represented exactly some loss of precision may occur unsigned long long Represent as float if the long long cannot be represented exactly some loss of precision may occur double Represent as float if result is too large result is undefined Represent as double if the int cannot be represented exactly some loss of precision may occur Represent as double if the long cannot be represented exactly some loss of precision may occur Represent as double if the long long cannot be represented exactly some loss of precision may occur Represent as double if the int cannot be represented exactly some loss of precision
103. incr_expr takes form Pe LVtt iv iv iv incr iv incr iv iv incr iv incr iv iv iv incr and w Iteration variable The iteration variable must be a signed integer not modified anywhere within the for loop It is implicitly made private for the duration of the for operation If not specified as lastprivate the iteration variable will have an indeterminate value after the operation completes b ub incr Loop invariant signed integer expressions No synchronization is performed when evaluating these expressions and evaluated side effects may result in indeterminate values Notes Program sections using the omp for pragma must be able to produce a correct result regardless of which thread executes a particular iteration Similarly program correctness must not rely on using a particular scheduling algorithm The for loop iteration variable is implicitly made private in scope for the duration of loop execution This variable must not be modified within the body of the for loop The value of the increment variable is indeterminate unless the variable is specified as having a data scope of lastprivate An implicit barrier exists at the end of the for loop unless the nowait clause is specified Restrictions are e The for loop must be a structured block and must not be terminated by a break statement e Values of the loop control expressions must be the same for all iterations of the loop e An omp for directive can
104. increase this area Do not enlarge the spill area unless the compiler issues a message requesting a larger spill area In case of a conflict the largest spill area specified is used Example If you received a warning message when compiling myprogram c and want to compile it specifying a spill area of 900 entries enter xlc myprogram c qspil1 900 Related Reading spnans Option Type Default Value pragma options Syntax qspnans qnospnans SPNANS NOSPNANS Purpose Generates extra instructions to detect signalling NaN on conversion from single precision to double precision The nospnans option specifies that this conversion need not be detected Appendix A Compiler Options 323 Notes The qhsflt option overrides the spnans option This option is obsolete Use qfloat nans in your new applications Related Reading srcmsg Option Type Default Value pragma options Syntax qsrcmsg qnosrcmsg SRCMSG NOSRCMSG Purpose Adds the corresponding source code lines to the diagnostic messages in the stderr file Notes The compiler reconstructs the source line or partial source line to which the diagnostic message refers and displays it before the diagnostic message A pointer to the column position of the error may also be displayed Specifying qnosrcmsg suppresses the generation of both the source line and the finger line and the error message simply shows the file line and column where the error occurred
105. issues an error message Examples of Pascal String Literals The compiler replaces trigraph sequences by the corresponding single character representation For example p pascal string becomes p pascal string The following are examples of valid Pascal string literals ANSI Mode p pascal string Each instance of a new line character and an immediately preceding backslash character is deleted splicing the physical source lines into logical ones For example p pascal string Two Pascal string literals are concatenated to form one Pascal string literal For example p ABC p DEF or p ABC DEF becomes O6ABCDEF For the macro ADDQUOTES define ADDQUOTES x x where xX is p pascal string or p pascal string becomes p pascal string Note however that ADDQUOTES This is not a p pascal string becomes This is not a p pascal string Extended Mode Is the same as ANSI mode except the macro definition would be define ADDQUOTES Ext x x Where x is the same as in the ANSI example p pascal string p pascal String 296 C for AIX User s Guide String Literal Processing The following describes how Pascal string literals are processed e Concatenating a Pascal string literal to a normal string gives a non Pascal string For example ABC pDEF gives ABCDDEF e A Pascal string literal cannot be concatenated with a wide string literal e
106. long long and convert long long to unsigned long long Preserve bit pattern sign function of sign bit lost unsigned short Preserve None Zero extend Zero extend Zero extend low order byte unsigned int Preserve Preserve None Preserve bit Zero extend low order bytes low order bytes pattern unsigned long Preserve Preserve Preserve bit None Zero extend low order bytes low order bytes pattern Preserve Preserve Preserve unsigned long long 462 C for AIX Users Guide Preserve None low order bytes Truncate if result Truncate if result is negative or too is negative or too large the result is large the result is undefined undefined low order bytes low order bytes low order bytes Truncate if result is negative or too large the result is undefined Convert to unsigned int and convert unsigned int to unsigned short Convert to int and convert int to unsigned char Convert to unsigned int and convert unsigned int to unsigned short Convert to int and convert int to unsigned char Convert to unsigned int and convert unsigned int to unsigned short Convert to int and convert int to unsigned char long double Type Conversions Floating point Types Truncate if result is negative or too large the result is undefined Truncate if result is negative or too large the result is undefined Truncate if result is negative or too large the result is undefined Truncate
107. mt Pe ee z ae ref a S ee E O 125 175 OE S pf fiogical or vertical bar po fright brace pf siontars tide ae e 486 C for AIX User s Guide Appendix N Problem Solving Message Catalog Errors Before the compiler can compile your program the message catalogs must be installed and the environment variables LANG and oe must be set to a language for which ue message catalog has been installed See information about setting these variables If you see the following message during compilation the appropriate message catalog cannot be opened Error occurred while initializing the message system in file message file where message _file is the name of the message catalog that the compiler cannot open This message is issued in English only You should then verify that the message catalogs and the environment variables are in place and correct If the message catalog or environment variables are not correct compilation can continue but all nondiagnostic messages are suppressed and the following message is issued instead No message text for message_number where message_number is the C for AIX internal message number This message is issued in English only To determine message catalogs which are installed on your system list all of the file names for the catalogs using the following command ls usr lib nls msg L vacx cat where L is the primary language environment locale selected during installation of
108. must ensure that you use a linker that is at least at the same release level as the newer of the compilers used to create the objects being linked 7 Some symbols which are clearly referenced or set in the source code may be optimized away by IPA and may be lost to debug nm or dump outputs Using IPA together with the g compiler will usually result in non steppable output The necessary steps to use IPA are 1 Perform preliminary performance analysis and tuning before compiling with the qipa option because the IPA analysis uses a two pass mechanism that increases compile and link time You can reduce some compile and link overhead by using the qipa noobject option 2 Specify the qipa option on both the compile and the link steps of the entire application or as much of it as possible Use suboptions to indicate assumptions to be made about parts of the program not compiled with qipa During compilation the compiler stores interorocedural analysis information in the O file During linking the qipa option causes a complete recompilation of the entire application Note If a Severe error occurs during compilation qipa returns RC 1 and terminates Performance analysis also terminates Example To compile a set of files with interorocedural analysis enter xlc c 03 c qipa xlc o product o qipa Here is how you might compile the same set of files improving the optimization of the second compilation and the speed of th
109. name file and line number line in a message Note debug_strncpy checks only the current default heap Therefore this debug support will not check all heaps within applications that have multiple user heaps To use _debug_strncpy you must compile with the debug memory qheapdebug compiler option This option maps all strncpy calls to debug_strncpy You do not have to change your source code in order for debug_strncpy to verify the heap Note The qheapdebug option maps all calls to other string functions and all calls to memory management functions including a heap specific version to their debug counterparts To prevent a call from being mapped parenthesize the function name Return Value _debug_strncpy returns a pointer to stringl1 Example This example contains a programming error The source string is too long for the destination buffer and the strncpy operation damages the heap include lt stdlib h gt include lt stdio h gt include lt string h gt define SIZE 10 int main void char source 1234567890123456789 char xdestination char return_string int index 15 destination char malloc SIZE strcpy destination abcdefg printf destination is originally s n destination return string strncpy destination source index printf After strncpy destination becomes s n n destination return 0 KEK KEK RK KKK EKER RRR RRR RR RRR ERR ERR RK ER RRR KERR KER KK k K EKER
110. of initializing a lock Each function initializes the lock associated with the parameter lock for use in subsequent calls void omp_init_nest_lock omp_nest_lock t lock omp_destroy_lock omp lock t lock These functions ensure that the pointed to lock variable lock is uninitialized omp_destroy_nest_lock omp_nest_lock_t lock omp set lock omp lock t lock Each of these functions blocks the thread executing the DON A 7 function until the specified lock is available and then sets the lock A simple lock is available if it is unlocked A nestable lock is available if it is unlocked or if it is already owned by the thread executing the function omp_set_nest_lock omp_nest_lock_t lock void omp_unset_lock omp_lock t lock These functions provide the means of releasing ownership of a lock void omp_unset_nest_lock omp_nest_lock_t lock int omp_test_lock omp lock t lock These functions attempt to set a lock but do not block execution of the thread int omp_test_nest_lock omp_nest_lock_t lock Note In the current implementation nested parallel regions are always serialized As a result omp_set_nested does not have any effect and omp_get_nested always returns 0 For complete information about OpenMP runtime library functions refer to the OpenMP C C Application Program Interface specification Appendix E Parallel Processing Facilities 401 Related Reading Run time Options for Parallel Processing Run
111. of or in addition to the default C for AIX runtime heap to improve the performance of your program Note Many readers will not be interested in creating their own heaps Using your own heaps is entirely optional and your applications will work perfectly well using the default memory management provided and used by the C for AIX runtime library If you want to improve the performance and memory management of your program multiple heaps can help you Otherwise you can ignore this section and any heap specific library functions Why Use Multiple Heaps Using a single runtime heap is fine for most programs However using multiple heaps can be more efficient and can help you improve your program s performance and reduce wasted memory for a number of reasons e When you allocate from a single heap you may end up with memory blocks on different pages of memory For example you might have a linked list that allocates memory each time you add a node to the list If you allocate memory for other data in between adding nodes the memory blocks for the nodes could end up on many different pages To access the data in the list the system may have to swap many pages which can significantly slow your program With multiple heaps you can specify which heap you allocate from For example you might create a heap specifically for the linked list The lists memory blocks and the data they contain would remain close together on fewer pages reducing the a
112. option conflicts and incompatibilities to occur C for AIX resolves these conflicts and incompatibilities in a consistent fashion as described in Related Reading Specifying Compiler Options on the Command Line Most options specified on the command line override both the default settings of the option and options set in the configuration file Similarly most options specified on the command line are in turn overridden b There are two kinds of command line options e qoption_keyword compiler specific e Flag options available to compilers on AIX systems q Options eo gop on aan a0 pe Suboni IOR 10 C for AIX User s Guide Command line options in the qoption_keyword format are similar to on and off switches If the option is specified more than once the last instance is recognized by the compiler For example qsource turns on the source option to produce a compiler listing qnosource turns off the source option so no source listing is produced For example xlc qnosource MyFirstProg c qsource MyNewProg c would produce a source listing for both MyNewProg c and MyFirstProg c because the last source option specified qsource takes precedence You can have multiple qoption_keyword instances in the same command line but they must be separated by blanks Option keywords can appear in either uppercase or lowercase but you must specify the q in lowercase You can specify any qoption_keyword before
113. overwritten at 0x000738ac The first eight bytes of the memory block in hex are AAAAAAAAAAAAAAAA This memory block was re allocated at line number 13 in _debug_heapm c Heap state was valid at line 14 of debug heapm c Memory error detected at line 17 of debug heapm c KK KKK KKK KERR KERR ERK ERE KR KK ERK KEKE RK ER KERR ARR KERR ERR ER REE KER KER EKER EKER Related Reading Appendix F C for AIX Debug Functions 411 _debug_malloc Allocate Memory Format include lt stdlib h gt also in lt malloc h gt void debug malloc size t size const char file size t line Language Level Extension _debug_malloc is the debug version of malloc Like malloc it reserves a block of storage of size bytes from the default heap _debug_malloc also sets all the memory it allocates to OxAA so you can easily locate instances where your program uses the data in the memory without initializing it first In addition debug malloc makes an implicit call to _heap check and stores the file name file and the line number line where the storage is allocated This information can later be used by the _heap_check _dump_allocated or dump_allocated_delta functions To use _debug malloc you must compile with the debug memory qheapdebug compiler option This option maps all malloc calls to _debug_malloc Note The qheapdebug option maps all calls to memory management functions including heap specific versions to their debug counterpart
114. page lists and briefly describes preprocessor directives available to you with C for AIX To get more information on any item listed here go to the reference page for that item Preprocessor Directives H Null directive specifying that no action be performed Defines a preprocessor macro Conditionally includes source text if the previous if ifdef ifndef or elif test fails Conditionally includes source text if the previous if ifdef ifndef or elif test fails Ends conditional text Defines text for a compile time error message Conditionally includes or suppresses portions of source code depending on the result of a constant expression Conditionally includes source text if a macro name is defined Conditionally includes source text if a macro name is not defined Inserts text from another source file Supplies a line number for compiler messages Specifies implementation defined instructions to the compiler Removes a preprocessor macro definition Null Preprocessor Directive The null directive performs no action It consists of a single on a line of its own The null directive should not be confused with the operator or the character that starts a preprocessor directive In the following example if MINVAL is a defined macro name no action is performed If MINVAL is not a defined identifier it is defined 1 ifdef MINVAL else define MINVAL 1 endi f Copyright IBM Corp 1995 1999 347
115. past the end of the buffer include lt stdlib h gt include lt string h gt include lt stdio h gt define BUF SIZE 20 int main void char buffer buffer2 char string buffer char calloc 1 BUF SIZE 1 1 for null terminator string char memset buffer A 10 printf nBuffer contents s n string memset buffer 10 B 20 return 0 kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk The output should be Buffer contents AAAAAAAAAA End of allocated object 0x00073c80 was overwritten at 0x00073c95 The first eight bytes of the memory block in hex are 4141414141414141 This memory block was re allocated at line number 12 in memset c Heap state was valid at line 14 of memset c Memory error detected at line 16 of memset c KK KK KKK KK KERR RARR ERK ERR EKER KK ERK ERK RK KERR ERK ERK ER ERR ER KER EKER EKER Related Reading _debug_realloc Reallocate Memory Block Format Appendix F C for AIX Debug Functions 417 include lt stdlib h gt also in lt malloc h gt void debug _realloc void ptr size t size const char file size_t line Language Level Extension _debug_realloc is the debug version of realloc Like realloc it reallocates the block of memory pointed to by ptr to a new size specified in bytes It also sets any new memory it allocates to OxAA So you can easily locate instances where your program tries to use the
116. point 4 9 3 Default file buffering is fully buffered File buffering can be set to line or to unbuffered with the setbuf function 4 9 3 A zero length file can exist 4 9 3 The character is not allowed in a valid file name 4 9 3 The same file can be opened multiple times 4 9 3 The remove function does not remove an open file The file is removed after it is closed 4 9 4 1 lf a file renamed by the rename function exists before a call to the function the file is renamed anyway 4 9 4 2 The output for p conversion in the fprintf and fscanf functions is a sequence of printable characters in an integer representation 4 9 6 1 and 4 9 6 2 In the fscanf function a hyphen character that is neither the first nor the last character in the scan list for conversion is interpreted as indicating a range of characters in the scan list For example you can express 0123456789 as 0 9 The stands for itself whenever it is the first or the last character in the scan list 4 9 6 2 Temporary Files tmpfile Function An open temporary file created by the tmpfile function is automatically deleted if the program terminates abnormally 4 9 4 3 errno Variable The errno variable is set to the value of the macro EINVAL 22 by the fgetpos or ftell function on failure 4 9 9 1 and 4 9 9 4 The perror function writes a message on the standard error output that describes the last error encountered by a system call or lib
117. point variable is implementation dependent On all compilers the storage size of a float variable is less than or equal to the storage size of a double variable 2 In extended mode the C compiler supports long float but this is a non portable language extension To declare a data object having a floating point type use the float specifier The float specifier has the form flot identifier pe long double long doubl The declarator for a simple floating point declaration is an identifier You can initialize a simple floating point variable with a float constant or with a variable or expression that evaluates to an integer or floating point number The storage class of a variable determines how you initialize the variable The following example defines the identifier pi as an object of type double double pi The following example defines the float variable real_number with the initial value 100 55 Static float real_number 100 55f 80 C for AIX User s Guide The following example defines the float variable float_var with the initial value 0 0143 float float_var 1 43e 2f The following example declares the long double variable maximum extern long double maximum The following example defines the array table with 20 elements of type double double table 20 Related Reading int long short p Specifier fi eseription Short short int Allocates 2 bytes of data storage int Allocates 4 bytes of data sto
118. pragma options source and similar directives enter xlc myprogram c gnoprint Related Reading O optimize Option Type Default Value pragma options flag Syntax 0 02 03 04 qoptimize qoptimize 4 qoptimize 5 OPTimize OPTimize 2 OPTimize 3 OPTimize 4 OPTimize 5 NOOPTimize OPTimize 0 qoptimize 3 goptimize 0 qoptimize 2 qnooptimize Purpose Optimizes code at a choice of levels during compilation Notes You can abbreviate qoptimize to qopt For example qnoopt is equivalent to qnooptimize Increasing the level of optimization may or may not result in additional performance improvements depending on whether additional analysis detects further opportunities for optimization Compilations with optimizations may require more time and machine resources than other compilations Optimization can cause statements to be moved or deleted and generally should not be specified along with the g flag for the dbx symbolic debug program The debugging information produced may not be accurate The levels of optimization are qNOOPTimize Same as qOPTimize 0 Performs only quick local optimizations such as constant folding and elimination of local common subexpressions This setting implies qstrict_induction unless qnostrict_induction is explicitly specified O qOPTimize Performs optimizations that the compiler developers considered the best combination for compilatio
119. preprocessor treat the result as a single value preprocess your source files using the P compiler option and then compile the resulting i file Identifiers that are partially built from a macro expansion may not be produced Therefore the following example contains two identifiers and results in a syntax error define d efg abcd Appendix D Preprocessor Directives and Related Information 349 Function Like Macros 350 C for AIX User s Guide To define a function like macro specify an identifier name followed by a parenthesized parameter list in parenthesis and the replacement tokens The parameters are imbedded in the replacement code White space cannot separate the identifier which is the name of the macro and the left parenthesis of the parameter list A comma must separate each parameter For portability you should not have more than 31 parameters for a macro Use function like macros in your program as follows In the body of your program source insert a defined function like macro name followed by a list of arguments in parentheses A comma must separate each argument Once the preprocessor identifies a function like macro invocation argument substitution takes place Parameters in the replacement code are replaced by the corresponding arguments Any macro invocations contained in an argument itself are completely replaced before the argument replaces its corresponding parameter in the replacement code Examples o
120. produce object files o files You can then link edit the resulting object files to create an executable file by invoking the compiler on these o files without using the c on page 242 option For example to produce object files for each of three programs testdata c testres c and testparm c you would enter xlc testdata c testres c testparm c c Then to produce an executable file named testprog from these three object files testdata o testres o and testparm o enter xlc testdata o testres o testparm o o testprog To combine several source files at compilation you can list the files on the command line when you use an invocation seMlucculs to produce a compiled file for each file you specify Or you can use the kainela r a 356 preprocessor directive to include the files in the primary source file so that one songs file is rouas This directive causes the text of a named secondary source file to be imbedded at the point where the include is encountered in the primary file Chapter 7 Writing C Programs 177 Related Reading Specifying Path Names for Include Files When you imbed one source file in another using the include preprocessor directive you must supply the name of the file to be included You can specify a file name either by using a full path name or by using a relative path name Using a Full Path Name to Imbed Files The full path name also called the absolute path name is the file s com
121. program was invoked is the first parameter Appendix Implementation Dependencies Overview 447 char argv Argument vector An array of pointers to character strings Each character string is a parameter supplied on the command line Valid pointers are from argv O to argv argc 1 argv 0 is the command name and argv 1 contains what was specified as the first argument to the command char envp Environment pointer An array of pointers to character strings Each character string is an environment parameter supplied to the program The array ends at the first null pointer array element with a value of zero An asynchronous terminal and a paired display and keyboard are the valid interactive devices 2 1 2 3 Related Reading Implementation Dependency Identifiers F 3 3 In an identifier without external linkage 219 characters beyond 31 for a total of 250 are significant 3 1 2 In an identifier with external linkage 244 characters beyond 6 for a total of 250 are significant 3 1 2 Case is significant in an identifier with external linkage Related Reading Implementation Dependency Characters F 3 4 The C for AIX compiler uses all source and execution characters explicitly specified by the ANSI C Standard 2 2 1 The C for AIX compiler recognizes the following escape sequence values 2 2 2 o o e O y oe O O t Sa S T 448 cC for AIX Users Guide Multibyte characters ar
122. reGAb Produces object code optimized for the RS64B processor If qtune is specified without qarch suboption the compiler uses qarch com You can use qtune suboption with qarch suboption e qarch suboption specifies the architecture for which the instructions are to be generated and e qtune suboption specifies the target platform for which the code is optimized Default The default setting of the qtune option depends on the setting of the qarch option e f qtune is specified without qarch the compiler uses qarch com e lf qarch is specified without qtune the compiler uses the default tuning option for the specified architecture Listings will show only TUNE DEFAULT Example To specify that the executable program testing compiled from myprogram c is to be optimized for a POWER hardware platform enter xlc o testing myprogram c qtune pwr Related Reading 7 ole LO OLDE OF 04 0 OM ViatiOr ON Vadge Option Type Default Value pragma options e Syntax Uname 332 C for AIX User s Guide Purpose Undefines the identifier name defined by the compiler or by the Dname option Notes The Uname option is not equivalent to the undef preprocessor directive It cannot undefine names defined in the source by the define preprocessor directive It can only undefine names defined by the compiler or by the Dname option The identifier name can also be undefined in your source program u
123. routines to see if they returned with any exception bits set Any such external routine must be a library routine or in user code that was not compiled with flttrap if trap_loc gt gt 1 amp Ox3ff 72 return 1 fmr found 34 C for AIX User s Guide Decode the instruction to identify the kind of operation x and the source and result registers fpe_loc trap_loc opcode op table trap_loc gt gt 1 amp Oxl1f frt_reg trap_loc gt gt 21 amp Oxlf fra_reg trap_loc gt gt 16 amp Oxl1f frb_reg trap_loc gt gt 11 amp Oxlf frc_reg trap_loc gt gt 6 amp Oxlf return 0 Install a trap handler and enable floating point exceptions The mask parameter indicates which exceptions should be enabled x as follows values are from usr include fptrap h Invalid Operation TRP_INVALID 0x00000080 Overflow TRP_OVERFLOW 0x00000040 Underflow TRP_UNDERFLOW 0x00000020 Division by Zero TRP_DIV_ BY ZERO Qx00000010 Inexact TRP_INEXACT Qx00000008 To enable multiple exceptions OR values together Note that the parameter is a pointer for FORTRAN call by reference void enable fp traps int mask Signal SIGTRAP void fhandler_ fp_enable mask Disable all floating point exceptions and remove trap handler void disable fp traps fp disable all Signal SIGTRAP SIG DFL Rounding Mode Rest
124. smaller than a specified size For best performance however use the inline keywords to choose the functions you want to inline rather than using automatic inlining An inline function can be declared and defined simultaneously If it is declared with one of the inline specifier keywords it can be declared without a definition The following code fragment shows an inline function definition Note that the definition includes both the declaration and body of the inline function _inline int add int i int j return i j Note The use of the inline specifier does not change the meaning of the function but inline expansion of a function may not preserve the order of evaluation of the actual arguments 204 C for AIX User s Guide Related Reading Chapter 7 Writing C Programs 205 206 C for AIX User s Guide Chapter 8 Using C for AIX with Other Programming Languages With the C for AIX compiler you can call functions written in other XL languages from your C program Similarly the other XL language programs can call functions written in C for AIX This and related pages give you information about how to use interlanguage calls in your C program You should already be familiar with the syntax of the languages you are using Related Reading Interlanguage Calling Conventions You should follow these recommendations when writing C for AIX code to call functions written in other languages e Avoid using uppercase le
125. specified The parameter names need not be unique If there is a conflict the last name specified is recognized For an invalid parameter list a warning is issued If a macro name is redefined with a new definition a warning will be issued and the new definition used undef When there are extra tokens no diagnostic message is generated Macro expansion e When the number of arguments on a macro invocation does not match the number of parameters a warning is issued e lf the token is present after the macro name of a function like macro it is treated as too few arguments as above and a warning is issued e Parameters are replaced in string literals and character literals e Examples define M 1 define N a a define O a b a b M no error N empty argument O empty first argument and too few arguments Text Output No text is generated to replace comments Related Reading Idbl128 longdouble Option Type Default Value pragma options noldbl1 28 LDBL128 Appendix A Compiler Options 289 Syntax qldb1128 qnoldb1128 qlongdouble qnolongdouble LDBL128 NOLDBL128 LONGDOUBLE NOLONGDOUBLE Purpose Increases the size of long double type from 64 bits to 128 bits Notes The qlongdouble option is the same as the qldbl128 option Separate libraries are provided that support 128 bit long double types These libraries will be automatically linked if you use any of th
126. specified arithmetic scalar or class type cast operator The cast operator is used for explicit type conversions char specifier A char is a built in data type character constant A character or an escape sequence enclosed in single quotation marks character set A group of characters used for a specific reason for example the set of characters a printer can print or a keyboard can support character variable A data object whose value can be changed during program execution and whose data type is char signed char or unsigned char comma expression An expression that contains two operands separated by a comma Although the compiler evaluates both operands the value of the expression is the value of the right operand If the left operand produces a value the compiler discards this value Typically the left operand of a comma expression is used to produce side effects complex number A complex number is made up of two parts a real part and an imaginary part A complex number can be represented by an ordered pair a b where a is the value of the real part and b is the value of the imaginary part The same complex number could also be represented as a bi where is the square root of 1 conditional compilation directive A preprocessor directive that causes the preprocessor to process specified source code in the file depending on the evaluation of a specific condition conditional expression A compound expression that
127. statements in the C source code Specifies that a given function never returns Tells the compiler that all references to an identifier are to be converted to name Lets you specify alternate optimization options for specific functions Specifies settings for compiler options in your source program Specifies that the point after a given routine marked reachable can be reached from a point other than the return from that routine Sets storage type for strings This directive must appear before any statements in the C source code Note The pragma page pragma skip pragma subtitle and pragma title directives are not recognized by the C for AIX compiler 364 C for AIX User s Guide oragma LOSES ou control parallel processing operations See pragmal for more information ale set of pragma alloca Preprocessor Directive The pragma alloca directive specifies that the function alloca size_t size is to allocate space for an object of size bytes The allocated space is put on the stack ee pragma aleca mr You must include the pragma alloca directive to have the compiler provide an inline version of alloca Alternatively the ma compiler option substitutes inline code for calls to function alloca without specifying the pragma alloca directive in the source code If pragma alloca is unspecified or if you do not use ma alloca is treated as a user defined identifier rather than as a buil
128. string is included in the object module The names of the debug versions are prefixed by debug_ for example debug malloc and they are defined in lt malloc h gt and lt stdlib h gt The functions provided are e debug _calloc e debug free e debug heapmin e _debug malloc e debug realloc The debug_malloc debug_realloc and debug free functions set the memory areas they affect toa specific repeating fill pattern See i for more information In addition to their usual behavior these functions also store information file name and line number about each call made to them Each call also automatically checks the heap by calling heap check described below Three additional debug memory management functions do not have regular counterparts 180 C for AIX User s Guide e dump allocated Prints information to stderr about each memory block currently allocated by the debug functions e dump allocated delta Prints information to file handle 2 about each memory block allocated by the debug functions since the last call to dump_allocated or dump allocated delta e heap check Checks all memory blocks allocated or freed by the debug functions to make sure that no overwriting has occurred outside the bounds of allocated blocks or in a free memory block The debug functions call heap check automatically and you can also call this function explicitly The _dump_allocated and dump _allocated_ delta functions must be explicitly call
129. that enumerations occupy 1 byte of storage qgenum 2 Specifies that enumerations occupy 2 bytes of storage qenum 4 Specifies that enumerations occupy 4 bytes of storage qgenum 8 Valid only in 64 bit compiler mode Specifies that enumerations occupy 8 bytes of storage RESET Valid in pragma enum statement only Resets the enum mapping rule to the rule that was in effect before the current mapping rule If no previous enum mapping rule was specified in the file the rule specified when the compiler was initially invoked is used The qenum small option allocates to an enum variable the amount of storage that is required by the smallest predefined type that can represent that range of enum constants By default an unsigned predefined type is used If any enum constant is negative a signed predefined type is used The enum constants are always of type int except for the following cases e f q64 is not specified and if the range of these constants is beyond the range of int enum constants will have type unsigned int and be 4 bytes long e If q64 is specified and if the range of these constants is beyond the range of int enum constants will have type long and be 8 bytes long Appendix A Compiler Options 255 The qenum 1 2 4 options allocate a specific amount of storage to an enum variable If the specified storage size is smaller than that required by the range of enum variables the requested size is kept but a warning is issue
130. the array An array can have more than one dimension The following example defines a one dimensional array that contains four elements having type char char list 4 The first subscript of each dimension is 0 The array list contains the elements list 0 list 1 listiz list 3 The following example defines a two dimensional array that contains six elements of type int int roster 3 2 Multidimensional arrays are stored in row major order When elements are referred to in order of increasing storage location the last subscript varies the fastest For example the elements of array roster are stored in the order roster 0 0 roster 0 1 roster 1 0 roster 1 1 roster 2 0 roster 2 1 You can leave the first and only the first set of subscript brackets empty in e Array definitions that contain initializations e extern declarations 86 C for AIX Users Guide e Parameter declarations In array definitions that leave the first set of subscript brackets empty the initializer determines the number of elements in the first dimension In a one dimensional array the number of initialized elements becomes the total number of elements In a multidimensional array the initializer is compared to the subscript declarator to determine the number of elements in the first dimension An unsubscripted array for example region instead of region 4 represents a pointer whose value is the address of the first element o
131. the compiler unless an explicit configuration file or command line compiler mode setting exists 3 Configuration file settings 4 Command line compiler options q32 q64 qarch qtune 5 Source file statements pragma options tune suboption The compilation mode actually used by the compiler depends on a combination of the settings of the q32 q64 qarch and qtune compiler options subject to the following conditions Compiler mode is set acording to the last found instance of the q32 or q64 compiler options If neither of these compiler options is chosen the compiler mode is set by the value of the OBJECT MODE environment variable Architecture target is set according to the last found instance of the qarch compiler option provided that the specified qarch setting is compatible with the compiler mode setting If the qarch option is not set the compiler assumes a qarch setting of com Tuning of the architecture target is set according to the last found instance of the qtune compiler option provided that the qtune setting is compatible with the architecture target and compiler mode settings If the qtune option is not set the compiler assumes a default qtune setting according to the garch setting in use Allowable combinations of these options are found in the Acceptable Compiler Mode and Processor Architecture Combinations table Possible option conflicts and compiler resolution of these conflicts are described b
132. the family of processors denoted by See the qarch compiler option for more information _CHAR_SIGNED Indicates that the default character type is signed Defined when the qchars signed compiler option is in effect See the qchars compiler option for more information _CHAR_UNSIGNED Indicates that the default character type is unsigned Defined when the qchars unsigned compiler option is in effect See the qchars compiler option for more information __ CLASSIC __ Macro defined when the classic language level is specified Defined using the pragma langlvl directive or the qlanglvl compiler option __ EXTENDED _ Allows additional language constructs provided by the C for AIX implementation Defined using the pragma langlvl directive or the qlanglvl compiler option 360 C for AIX User s Guide FUNCTION _ HOS AIX __IBMC__ __IBMSMP _ILP32 _LONG LONG _LONGDOUBLE128 _LP64 MATH _OPENMP POWER O SAA SAAL2 SIR __THW_INTEL__ __THW_RS6000__ _xIC__ Indicates the name of the function being compiled Indicates the host operating system is AIX Macro contains the version number of the compiler for example _IBMC___ 450 This macro should be used innew code Macro defined when the when the qsmp compiler option is selected Defined if the compiler is using the 32 bit data model This data model is used when compiling programs for 32 bit mode This macro should not be user defined or redefined Macr
133. the last name specified is honored For an invalid parameter list a warning is issued If a macro name is redefined with a new definition a warning will be issued and the new definition used undef When there are extra tokens no diagnostic message is generated Macro expansion e When the number of arguments on a macro invocation does not match the number of parameters a warning is issued e lf the token is present after the macro name of a function like macro it is treated as too few arguments as above and a warning is issued e Parameters are replaced in string literals and character literals e Examples define M 1 define N a a define O a b a b M no error N empty argument 0 empty first argument and too few arguments 166 C for AIX User s Guide No text is generated to replace comments Related Reading saal2 C Deviations from SAA Level 2 C saal2 level C deviates from the SAA C definition as follows e The _Packed attribute for structures and unions is not supported by the C compiler component of C for AIX The qalign packed compiler option provides some of the function of the attribute e Record input output is not supported by the AIX Version 3 2 operating system and is not available on the C compiler SAA Level 2 defines record input output e AIX Version 3 2 operating system error conditions for the following differ from those of SAA Level 2 acos asi
134. the program that is being run If the name cannot be determined the first element in argv points to a null character This name is counted as one of the arguments to the function main For example if only the program name is entered on the command line argc has a value of 1 and argv 0 points to the program name Regardless of the number of arguments entered on the command line argviargc always contains NULL Related Reading 144 C for AIX User s Guide Example of the main Function The following program backward prints the arguments entered on a command line such that the last argument is printed first include lt stdio h gt int main int argc char argv while argc gt 0 printf s argv argc Invoking this program from a command line with the following backward stringl string2 gives the following output string stringl The arguments argc and argv would contain the following values C argv 0 pointer to string backward argv 1 pointer to string string1 argv 2 pointer to string string2 Related Reading Program Statement Keywords break A break statement lets you end an iterative do for while or switch statement and exit from it at any point other than the logical end p gt break In an iterative statement the break statement ends the loop and moves control to the next statement outside the loop Within nested statements the break statement ends only
135. time options affecting parallel processing are specified in the XLSMPOPTS environment variable This environment variable which must be set before you run an application uses syntax of form XLSMPOPTS option_and_args option_and_args Parallelization run time options can also be specified using OMP environment variables When OMP and XLSMPOPTS run time options conflict OMP options will prevail Run time options fall into different categories as described below Scheduling Algorithm Options schedule algorith n his option specifies the scheduling algorithm used for loops not explictly assigned a scheduling alogorithm with the ibm schedule pragma Valid options for algorithm are e guided e affinity e dynamic e static If specified the value of n must be an integer value of 1 or greater The default is scheduling algorithm is static See E pragma ibm 8d for a description of these algorithms Parallel Environment Options parthds num num represents the number of parallel threads requested which is usually equivalent to the number of processors available on the system Some applications cannot use more threads than the maximum number of processors available Other applications can experience significant performance improvements if they use more threads than there are processors This option gives you full control over the number of user threads used to run your program The default value for num is the number o
136. to gather variable definitions into one source file and declare references to those variables in any source files that use them This procedure makes definitions easy to find and change You can also organize constants and macros into separate files and include them into source files as needed You can use the include directive to imbed such source files into other source files Directives in a source file apply to that source file and its included files only Each directive applies only to the part of the file and included files following the directive The C for AIX compiler looks for a function called main in the source code and uses it as the entry point name If a program contains more than one function definition only one of these functions can be named main If the program contains only one function definition that function must be called main Related Reading Example of a Simple C Program The source for a simple C program is shown below A Simple C Program Chapter 7 Writing C Programs 175 x xx This is an example of a simple C program Kx include lt stdio h gt standard I 0 library header that contains macros and function declarations ie printf used below include lt math h gt standard math library header that contains macros and function declarations ie cos used below x define NUM 46 0 Preprocessor directive x double x 45 0 External variable definitions x double y NUM int mai
137. to long double None Appendix I Implementation Dependencies Overview Convert to long double 463 long double Convert to float Represent as double if result is too large to be represented as double result is undefined Converting Pascal String LiteralsThe qmacpstr option converts Pascal string literals of the form pABC into null terminated strings where the first byte contains the length of the string Integral PromotionThe default compiler action is for integral promotions to convert a char short int int bitfield or their signed or unsigned types or an enumeration type to an int Otherwise the type is converted to an unsigned int The qupconv option promotes any unsigned type smaller than an int to an unsigned int instead of to an int Related Reading Synchronization of Stores and Loads to I O Space Stores and loads to I O space must be separated from other store and load operations by synchronization instructions These synchronization instructions allow the compiler to synchronize the execution of the code block The C for AIX compiler provides two built in functions that you can use to specify the type of synchronization and where and how it should take place For C source programs the two functions are e extern void _iospace_eieio void e extern void _iospace_sync void Use the function __ iospace_eieio Enforced In order Execution for I O when you want to synchronize cache inhibited mem
138. to the optimizer that external and static variables are not changed by the called function The pragma options keyword isolated_call must be specified at the top of the file before the first C statement You can use the pragma isolated_call directive at any point in your source file Example To compile myprogram c specifying that the functions myfunction int and classfunction double do not have side effects enter xlc myprogram c qisolated_call myfunction classfunction Related Reading Option Type Default Value pragma options tag See toto Syntax Ldirectory Purpose Searches the path directory for library files specified by the lkey option Notes If the Ldirectory option is specified both in the configuration file and on the command line the paths specified in the configuration file are searched first Default The default is to search only the standard directories Example To compile myprogram c so that the directory usr tmp old is searched for the library libspfiles a enter xlc myprogram c lspfiles L usr tmp old Appendix A Compiler Options 285 Related Reading Option Type Default Value pragma options stag Sete Syntax lkey Purpose Searches the specified library file libkey so and then libkey a for dynamic linking or just ibkey a for static linking Notes The actual search path can be modified with the Ldirectory option See B brtl and bstatic bdynamicfor information on spec
139. tokens and sequences of white space A single white space replaces each comment A source file cannot end with a partial token or comment 4 Preprocessing directives are run and macros are expanded 5 Escape sequences in character constants and string literals are replaced by their equivalent values 6 Adjacent string literals are concatenated The rest of the compilation process operates on the preprocessor output which is syntactically and semantically analyzed and translated and then linked as necessary with other programs and libraries Related Reading Preprocessor Macros You can use the define preprocessor directive to define a macro that assigns a value to an identfier The preprocessor replaces subsequent occurences of that identifier with its assigned value until the identifier is undefined with the undef preprocessor directive or until the end of the program source is reached whichever comes first There are two basic types of macro definitions that you can use to assign a value to an identifer Object like Macros Replaces a single identifier with a specified token or constant value Chapter 6 The C Language 59 Function like Macros Associates a user defined function and argument list to an identifier When the preprocessor encounters that identifier in the program source the defined function is inserted in place of the identifier along with any corresponding arguments Related Reading Conditional Compilati
140. two digit code indicating the C for AIX compiler component that issued the message cc can have the following values 00 code generating or optimizing message 01 compiler services message 06 message specific to C for AIX compiler 40 message specific to C for AIX compiler 41 message specific to C for AIX compiler 46 message specific to C for AIX compiler backend 86 message specific to interprocedural analysis IPA nnn is the message number severity is a letter representing the severity of the error text is a message describing the error Diagnostic messages have the following format when the qsrcmsg option is specified x 15dd nnn severity text where x is a letter referring to a finger in the finger line To help you find the exact point of the error in the line when you use the qsrcmsg option a finger line is produced below the source code line if the error is applicable to a specific column in the source line For example 10 int add int int EE PEF sel eas a 1506 166 S Definition of function add requires parentheses Chapter 3 Using the C for AIX Compiler 21 b 1506 172 S Parameter type list for function add contains parameters without identifiers c 1506 172 S Parameter type list for function add contains parameters without identifiers The finger line may also be produced in the source listing if you specify the qsource option Related Reading 22 C for AIX User s Guide Chap
141. two operands and one operator bit field A member of a structure or union that contains 0 or more bits block See asd block statement Any number of data definitions declarations and statements that appear between the symbols left brace and right brace boundary alignment The position in main storage of a fixed length field such as halfword or doubleword on an integral boundary for that unit of information For example a word boundary is a storage address evenly divisible by four break statement A language control statement that contains the word break and a semicolon It is used to end an iterative or a switch statement by exiting from it at any point other than the logical end Control is passed to the first statement after the iteration or switch statement buffer flush A process that removes the contents of a buffer After a buffer flush the buffer is empty Copyright IBM Corp 1995 1999 489 C C library A system library that contains common C language subroutines for file access string operators character operations memory allocation and other functions case clause In a switch statement a case label followed by any number of statements case label The word case followed by a constant expression and a colon When the selector evaluates the value of the constant expression the statements following the case label are processed cast expression A cast expression explicitly converts its operand to a
142. type char short or int or any enumeration type and is equivalent to sizeof int sizeof x 1 Except in preprocessor directives you can use a sizeof expression wherever an integral constant is required One of the most common uses for the sizeof operator is to determine the size of objects that are referred to during storage allocation input and output functions Another use of sizeof is in porting code across platforms You should use the sizeof operator to determine the size that a data type represents For example sizeof int Using the sizeof operator on a bit field is not permitted in ansi mode It is allowed in extended mode and returns the same result as sizeof int When applied to a C enumeration constant sizeof always returns 4 because enumeration constants in C always have type int or unsigned int When applied to an enumeration compiled under the qenum small option the result of the sizeof operation is the size of the predefined type used to allocate storage for the enumeration Chapter 6 The C Language 123 Related Reading Binary Operators Multiplication The multiplication operator yields the product of its operands The operands must have an arithmetic type The result is not an lvalue The usual arithmetic conversions on the operands are performed Because the multiplication operator has both associative and commutative properties the compiler can rearrange the operands in an expres
143. use stanza apply if no value is provided in the local or default stanza For comma separated lists the values from the use stanza are added to the values from the local stanza The path name of the xlc compiler component The default is usr vac bin xlc Specifying Compiler Options for Architecture Specific 32 or 64 bit Compilation You can use C for AIX compiler options to optimize compiler output for use on specific processor architectures You can also instruct the compiler to compile in either 32 or 64 bit mode The compiler evaluates compiler options in the following order with the last allowable one found determining the compiler mode 1 Internal default 32 bit mode 2 OBJECT MODE environment variable setting as follows OBJECT MODE User selected compilation mode behavior unless overridden by configuration file or Setting not set 32 command line options 32 bit compiler mode 32 bit compiler mode 14 C for AIX User s Guide OBJECT MODE User selected compilation mode behavior unless overridden by configuration file or Setting command line options 64 64 bit compiler mode 32 64 Fatal error and stop with following message 1501 054 OBJECT MODE 32 64 is not a valid setting for the compiler unless an explicit configuration file or command line compiler mode setting exists any other Fatal error and stop with following message 1501 055 OBJECT MODE setting is not recognized and is not a valid setting for
144. usual arithmetic conversions on each operand are performed The result has the same type as the converted operands and is not an lvalue Because the bitwise exclusive OR operator has both associative and commutative properties the compiler can rearrange the operands in an expression that contains more than one bitwise exclusive OR operator even when the sub expressions are explicitly grouped with parentheses The following example shows the values of a b and the result of a b represented as 32 bit binary numbers bit pattern of a 00000000000000000000000001011100 bit pattern of b 00000000000000000000000000101110 bit pattern ofa b 00000000000000000000000001110010 Chapter 6 The C Language 129 Bitwise Inclusive OR The bitwise inclusive OR operator compares the values in binary format of each operand and yields a value whose bit pattern shows which bits in either of the operands has the value 1 If both of the bits are 0 the result of that bit is 0 otherwise the result is 1 Both operands must have an integral type The usual arithmetic conversions on each operand are performed The result has the same type as the converted operands and is not an lvalue Because the bitwise inclusive OR operator has both associative and commutative properties the compiler can rearrange the operands in an expression that contains more than one bitwise inclusive OR operator even when the subexpressions are explicitly grouped with paren
145. v Related Reading Option Type Default Value pragma options 7 Syntax 336 C for AIX User s Guide Worogram options Purpose Passes the listed options to the designated compiler program program can be Program Description a Assembler b Compiler back end c Compiler front end I Interprocedural Analysis tool 1 linkage editor p compiler preprocessor Notes When used in the configuration file the W option accepts the escape sequence backslash comma to represent a comma in the parameter string Example To compile myprogram c so that the option pg is passed to the linkage editor 1 and the assembler a enter xlc myprogram c Wl a pg In a configuration file use the sequence to represent the comma Wl a pg Related Reading Option Type Default Value pragma options stag Sete Syntax W Purpose Requests that warnings and lower level messages be suppressed Specifying this option is equivalent to specifying qflag e e Example To compile myprogram c so that no warning messages are displayed enter xlc myprogram c w Related Reading Appendix A Compiler Options 337 warn64 Option Type Default Value pragma options aoption rowan Syntax qwarn64 Purpose Enables checking for possible long to integer truncation Notes All generated messages have level Informational This option functions in either 32 or 64 bit compiler modes In 32 bit mode it functions a
146. vacpp 1lib profiled L lib profiled L usr lib profiled L usr vacpp 1ib 1hC 1hmd qansialias qldb1128 qthreaded D THREAD SAFE D_VACPP MULTI D AIX PTHREADS D7 D AIX32_THREADS aliased acrtOr AIX POSIX Draft 7Threads DEFLT lib crt0 o lib mcrt0 o lib gcert0 o L usr lib threads lpthreads_ compat lpthreads lc_r lc L lib profiled L usr lib profiled L usr vac 1ib 1hmd qansialias qthreaded D THREAD SAFE D_VACPP MULTI D AIX PTHREADS D7 DEFLT lib crt0 o lib mcrt0 o lib gcrt0 o L usr lib threads Ipthreads_ compat lpthreads 1c128 1lc_r lc L lib profiled L usr lib profiled L usr vac 1lib 1hmd qansialias qthreaded D THREAD SAFE D_VACPP MULTI D AIX PTHREADS D7 q1db1128 aliased as cc_r AIX POSIX Draft 7Threads DEFLT lib crt0 o lib mcrt0 o lib gcrt0 o L usr lib threads lpthreads_compat lpthreads lc_r lc L lib profiled L usr lib profiled L usr vac lib 1hmd qlanglvl extended qnoro qnoroconst qthreaded D_THREAD_SAFE D__VACPP_MULTI__ D_AIX_PTHREADS_D7 DEFLT lib crt0 o lib mcrt0 o lib gcrt0 o L usr lib threads lpthreads_ compat lpthreads 1c128 1lc_r lc L lib profiled L usr lib profiled L usr vac 1ib 1hmd qlanglvl extended qnoro qnoroconst qthreaded D_ THREAD SAFE D_VACPP_ MULTI _ D AIX_PTHREADS D7 x x1C C compiler aliased as x1C_r7 AIX POSIX Draft 7Threads xlC_ r7 use crt mcrt gcrt libraries2 proflibs hdlibs options DEFLT li
147. value 3 to alpha alpha deltat omega 4 Any number of expressions separated by commas can form a single expression The compiler evaluates the leftmost expression first The value of the rightmost expression becomes the value of the entire expression For example the value of the expression intensity shade increment rotate direction is the value of the expression rotate direction The primary use of the comma operator is to produce side effects in the following situations e Calling a function e Entering or repeating an iteration loop e Testing a condition e Other situations where a side effect is required but the result of the expression is not immediately needed To use the comma operator in a context where the comma has other meanings such as in a list of function arguments or a list of initializers you must enclose the comma operator in parentheses For example the function f a t 3 t 2 c has only three arguments the value of a the value 5 and the value of c The value of the second argument Is the result of the comma expression in parentheses C 3 t 2 136 C for AIX User s Guide which has the value 5 Related Reading Examples Using the Comma Operator The table below gives some examples of the uses of the comma operator if fO i i gt l An if statement in which function f is called variable i is incremented and x variable i is tested against a
148. value The first two expressions within this comma expression are evaluated before the expression i gt 1 Regardless of the results of the first two expressions the third is evaluated and its result determines whether the if statement is processed func a f a A function call to func in which a is incremented the resulting value is passed to a function f and the return value of f is passed to func The function func is passed only a single argument because the comma expression is enclosed in parentheses within the function argument list Related Reading Arithmetic Conversions Table Arithmetic conversions are used for matching operands of arithmetic operators and proceed in the following order One operand has unsigned long long int type The other operand is converted to unsigned long long int One operand has unsigned int type and the other The operand with unsigned int type is converted to long operand has long int type and the value of the unsigned int int can be represented in a long int One operand has unsigned int type and the other Both operands are converted to unsigned long int operand has long int type and the value of the unsigned int cannot be represented in a long int One operand has long int type The other operand is converted to long int Chapter 6 The C Language 137 Operand Type Functions Function Declarations A function declaration establishes the name and the paramet
149. value having type double to a value having type float Expansion conversions Change the data type of a value to a larger size data type for example a value having type float to a value having type double Pointer conversions Change the data type to which a pointer refers or change an integral type to a pointer void conversions Discard the value of a function call volatile conversions Give a nonvolatile data object the volatile attribute The following sections describe these conversions Reduction Conversions Integral Reduction The compiler converts an integral value to a narrower type for example a long to a short the compiler truncates the value by discarding the most significant bits double or long double to float The compiler converts a double precision floating point value long double or double to a single precision floating point value float the compiler rounds off the double precision value Floating Point to Integral The language does not define the method of converting floating point values to integral values The compiler drops the fraction part of the floating point value Integral to Floating Point The C language does not prohibit integral sizes from having a higher precision than the floating point sizes If a higher precision integer is converted to a float the resulting float might experience a loss of precision Chapter 6 The C Language 169 Expansion Conversions Floating Point Expansion Although ma
150. volatile group In both examples above only the structure variable group receives the volatile qualifier Similarly if you specified the const keyword instead of volatile only the structure variable group receives the const qualifier The const and volatile qualifiers when applied to a structure or union also apply to the members of the structure or union Although enumeration structure and union variables can receive the volatile or const qualifier enumeration structure and union tags do not carry the volatile or const qualifier For example the blue structure does not carry the volatile qualifier 116 C for AIX Users Guide volatile struct whale int weight char name 8 beluga Struct whale blue The keywords volatile and const cannot separate the keywords enum struct and union from their tags You cannot declare or define a volatile or const function but you can define or declare a function that returns a pointer to a volatile or const object You can put more than one qualifier on a declaration but you cannot specify the same qualifier more than once on a declaration If you put a type definition in the same declaration as a definition of a variable having the volatile or const qualifier the qualifier applies to that variable only For example enum shape round square triangular oblong volatile object enum shape appearance The variable object is defined as volatile The variable appearance does not hav
151. which also lets you specify what optional outputs are produced Optional outputs are shown in the diagram by the broken lines Descriptions of the steps follow below Design and Code Compile Linkage Editor Run and Test Involves designing a program to meet a specified requirement and creating the programming language text files that will comprise the program source After checking for syntactical correctness converts the programming language source files into machine readable instructions where C variables are associated with memory addresses and C statements are turned into a series of machine language instructions The compiler can produces various forms of output depending on the compiler options selected Links compiler output with external modules requested by the compiled program C programs can use routines from C libraries or any object or archive file from the IBM XL family of languages C programs can also use modules produced by the current or previous compilations As well as linking the external modules the linkage editor resolves addresses within the object module This stage can be both the final step in program development or it can be an intermediate point in the program design and implementation process A program s design commonly is further refined as a result of information gathered during testing Copyright IBM Corp 1995 1999 173 Related Reading Creating and Naming a C Source File A C program s
152. white space to make the source code more readable White space includes blanks horizontal and vertical tabs new lines form feeds and comments Related Reading Copyright IBM Corp 1995 1999 45 Comments Comments begin with the characters end with the characters and can span more than one line You can put comments anywhere the language allows white space Multibyte characters can be included in a comment Comments are replaced during preprocessing by a single space character If the compiler option is in effect when you compile a C program double slashes also specify the beginning of a comment The comment ends at the next newline character The FE on page 253 and compiler options affect how comments appear in the compiler listing Note The or characters found in a character constant or string literal do not start or end comments You cannot nest comments Each comment ends at the first occurrence of For example in the following code segment the comments are highlighted 1 A program with nested comments 2 3 include lt stdio h gt 4 5 jint main void 6 7 test_function 8 9 10 int test_function void 11 12 int number 13 char letter 14 15 number 55 16 letter A 17 number 44 18 19 return 999 20 In test_function the compiler reads the in line 14 through the in line 17 as a comment and line 18 as C language code causing erro
153. with _r invocation modes and qnothreaded when compiling with other invocation modes Related Reading tune Option Type Default Value pragma options Syntax qtune suboption TUNE suboption Purpose Specifies the architecture system for which the executable program is optimized Notes Allowable values for suboption are auto Automatically detects the specific architecture of the compiling machine Use this suboption only if the execution environment is the same as the compilation environment Appendix A Compiler Options 331 403 Produces object code optimized for the PowerPC 403 processor 601 Produces object code optimized for the PowerPC 601 processor 602 Produces object code optimized for the PowerPC 602 processor 603 Produces object code optimized for the PowerPC 603 processor 604 Produces object code optimized for the PowerPC 604 processor p2sc Produces object code optimized for the PowerPC P2SC processor pwr Produces object code optimized for the POWER hardware platforms pwr2 Produces object code optimized for the POWER2 hardware platforms pwr2s Produces object code optimized for the POWER2 hardware platforms avoiding certain quadruple precision instructions that would slow program performance pwr3 Produces object code optimized for POWERS processors pwrx Produces object code optimized for the POWER2 hardware platforms same as qtune pwr2 E Produces object code optimized for the RS64A processor
154. xlc stem c F home tools test3 new cfg myc qproclocal sort count where new cfg is a custom configuration file You can specify flags that do not take arguments in one string For example xlc Ocv file c has the same effect as xlc 0 c v file c and compiles the C source file file c with optimization O and reports on compiler progress v but does not invoke the linkage editor c A flag option that takes arguments can be specified as part of a single string but you can only use one flag that takes arguments and it must be the last option specified For example you can use the o flag to specify a name for the executable file together with other flags only if the o option and its argument are specified last For example Chapter 3 Using the C for AIX Compiler 11 xlc Ovotest test c has the same effect as xlc 0 v otest test c Most flag options are a single letter but some are two letters Note that pg extended profiling is not the same as p g profiling p and generating debug information g Take care not to specify two or more options in a single string if there is another option that uses that letter combination Related Reading Specifying Compiler Options in Your Program Source Files To specify compiler options in your program source files use the preprocessor directive pragma options compiler_options If you specify more than one compiler option separate the options using a blank sp
155. y x y define nwsl x y x y define nws2 x y x y i in ANSI ISO C For to function the same way as EF 4 there can be no spaces between the operator and the PA Related Reading Appendix D Preprocessor Directives and Related Information 379 380 C for AIX User s Guide Appendix E Parallel Processing Facilities pragma Preprocessor Directives for Parallel Processing The pragma directives on this page give you control over how the compiler handles parallel processing in your program These pragmas fall into two groups IBM C for AlX specific directives and directives conforming to the OpenMP Application Program Interface specification All of the following pragmas have effect only if the qsmp option is specified If the qsmp option is not specified syntax checking of the pragmas is still performed even though corresponding code is not generated You can instruct the compiler to ignore all parallel processing related pragma directives by specifying the qignprag ibm omp compiler option Directives apply only to the statement or statement block immediately following the directive nragma ibm critical Instructs the compiler that the statement or statement block immediately following this pragma is a critical section Asserts that specified function calls within the chosen loop have no loop carried dependencies Asserts that iterations of the chosen loop are independent and that the loop can
156. you with the C for AIX compiler To get more information on any item listed here go to the reference page for that item Preprocessor Macro Operators Converts a parameter of a function like macro into a character string literal Concatenates two tokens in a macro ignoring white space between macro tokens and operators Concatenates two tokens in a macro preserving white Space between macro tokens and operators Preprocessor Macro Operator The single number sign operator converts a parameter of a function like macro into a character string literal For example if macro ABC is defined using the following directive define ABC x x all subsequent invocations of the macro ABC would be expanded into a character string literal containing the argument passed to ABC For example Result of Macro Expansion The operator should not be confused with the directive Use the operator in a function like macro definition according to the following rules e A parameter following operator in a function like macro is converted into a character string literal containing the argument passed to the macro e White space characters that appear before or after the argument passed to the macro are deleted e Multiple white space characters imbedded within the argument passed to the macro is replaced by a single space character e If the argument passed to the macro contains a string literal and if a backslash charact
157. 0 BRK kk kk kkk kk kk kk ERR ER KER ERR ER KER KER KERR ERE ER KER kk kk kkk KEKE REE RK EKER RRR RE RRR The output should be similar to End of allocated object 0x00073c80 was overwritten at 0x00073c8a The first eight bytes of the memory block in hex are 636F6D7075746572 This memory block was re allocated at line number 12 in strncat c Heap state was valid at line 13 of strncat c Memory error detected at line 17 of strncat c KK KK KKK KK KERR KERR ERK EK KER ER KK ERK EKER ERK KERR RRR RRR KER KER EERE RE REE EKER Related Reading _debug_strncpy Copy Strings Format Appendix F C for AIX Debug Functions 423 include lt string h gt char debug strncpy char stringl const char string2 size_t count const char file size t line Language Level Extension _debug_strncpy is the debug version of strnepy Like strncpy it copies count characters of string2 to string1 If count is less than or equal to the length of string2 a null character 0 is not appended to the copied string If count is greater than the length of string2 the stringl result is padded with null characters 0 up to length count _debug_strncpy validates the heap after copying the strings to the target location and performs this check only when the target is within a heap debug _strncpy makes an implicit call to heap_check If _debug_strncpy detects a corrupted heap when it makes a call to heap check debug_strncpy will report the file
158. 5 int i int letter_count 0 char pointer for i 0 i lt SIZE i for each string for each character for pointer strings i pointer O pointer if a number if pointer gt 0 amp amp pointer lt 9 break letter _countt printf letter count d n letter count The program produces the following output letter count 4 The following example is a switch statement that contains several break statements Each break statement indicates the end of a specific clause and ends the switch statement 146 C for AIX Users Guide include lt stdio h gt enum morning afternoon evening timeofday morning int main void switch timeofday case morning printf Good Morning n break case evening printf Good Evening n break default printf Good Day eh n Related Reading nreak on nadae 145 continue A continue statement lets you end the current iteration of a loop Program control is passed from the continue statement to the end of the loop body ee continue rq The continue statement ends the processing of the action part of an iterative do for or while statement and moves control to the condition part of the statement If the iterative statement is a for statement control moves to the third expression in the condition part of the statement then to the second expression the test in the condition part of the statement
159. 5 KK KK KKK KEKE KK kk kk kkk kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkx 6 7 include lt stdio h gt 8 9 int main void 10 begin main x 11 void tally void declaration of function tally 12 extern float total first declaration of total x 13 14 printf Enter the purchase amount n 15 tally 16 printf nWith tax the total is 2f n total 17 18 return 0 19 end main File 2 EEk kk k kk kk kk k kk kk kk k kk kk k k k kk kk kkk k kkk kkk kK KKK KRKK KKK KRKK KKK K xx This file defines the function tally kx KKK KK KKK KK kkk kkk kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkx 1 2 3 4 include lt stdio h gt 6 define tax rate 0 05 7 8 void tally void 9 begin tally 10 float tax 11 extern float total second declaration of total 12 13 scanf f amp total 14 tax tax_rate total 15 total tax 16 end tally File 3 1 float total When this program is run interaction with it could produce Output Enter the purchase amount Input 99 95 Output With tax the total is 104 95 The following program shows extern variables used by two functions Because both functions main and sort can access and change the values of the extern variables string and length main does not have to pass parameters to sort BRK RRR RR KK ERK KERR RE RRR RRR k k k RRR RK ER ERE RR RRR EKER KER ERR ERK ERE EKER Kk Kk xx Sorted string program this examp
160. 9 Related Reading _debug_uheapmin Free Unused Memory in User Heap Format include lt umalloc h gt int debug uheapmin Heap t heap const char file size t line Language Level Extension _debug_uheapmin is the debug version of _uheapmin Like _uheapmin it returns all unused memory blocks from the specified heap to the operating system To return the memory _debug_uheapmin calls the release_fn you supplied when you created the heap with _ucreate If you do not supply a release_fn debug _uheapmin has no effect and returns 0 In addition debug uheapmin makes an implicit call to uheap_check to validate the heap _debug_uheapmin works just like debug heapmin except that you specify the heap to use _debug_ heapmin always uses the default heap To use _debug_ uheapmin you must compile with the debug memory qheapdebug compiler option This option maps all uheapmin calls to debug uheapmin Note The qheapdebug option maps all calls to memory management functions including heap specific versions to their debug counterparts To prevent a call from being mapped parenthesize the function name Return Value If successful debug uheapmin returns 0 A nonzero return value indicates failure If the heap specified is not valid debug uheapmin generates an error message with the file name and line number where the call to debug uheapmin was made 430 C for AIX User s Guide Example This example creates a heap and allocat
161. AIX User s Guide double num int retnum void ary 2 aryL0 void funcl ary 1 void func2 int ary 0 calls funcl void double ary 1 num calls func2 int funcl void int number 3 return number void func2 double a a 333 3333 The following example is a complete definition of the function sum int sum int x int y return x y The function sum has external linkage returns an object that has type int and has two parameters of type int declared as x and y The function body contains a single statement that returns the sum of x and y The following example contains a function declarator sort with table declared as a pointer to int and length declared as type int Note that arrays as parameters are implicitly converted to a pointer to the type void sort int table int length int i j temp for i 0 i lt length 1 i for j i 13 j lt length j if table i gt table j temp table i table i table j table j temp The following examples contain prototype function declarators double square float x int area int x int y Static char search char The following example shows how a typedef function can be used in a function declarator typedef struct tm fmt int minutes int hours char am_pm struct_t long time _seconds struct_t arrival The following function set_date decl
162. ARCH_COM DEFAULT not selectable pwr pwr2 pwr2s pwr3 pwrx p2sc 601 602 603 604 403 rs64a rs64b _ARCH_PWR _ARCH_PWR2 _ARCH_PPC 604 32 bit mode pwr3 64 bit mode ARCH_PPC _ARCH_PPCGR Chapter 3 Using the C for AIX Compiler 17 Default qtune suboption _ARCH_PWR _ARCH_PWR2 _ARCH_PWR2S _ARCH_PWR _ARCH_PWR2 _ARCH_P2SC ARCH_601 _ARCH_PPC _ARCH_602 _ARCH_PPC _ARCH_PPCGR _ARCH_603 _ARCH_PPC _ARCH_PPCGR _ARCH_604 _ARCH_PPC _ ARCH_PPCGR _ARCH_PWR3 _ARCH_ PPC RS 6000 Models _ARCH_RS64A S70 S71 _ARCH_ PPC RS 6000 Models _ARCH_RS64B S70 S71 Compiler Message and Listing Information When the compiler encounters a programming error while compiling a C source program it issues a diagnostic message to the standard error device The compiler issues messages specific to the C language and XL messages common to all XL compilers If you specify the compiler option qsrcmsg and the error is applicable to a particular line of code the reconstructed source line or partial source line is included with the error message in the stderr file A reconstructed source line is a preprocessed source line that has all the macros expanded 18 C for AIX User s Guide If the error is identifiable within the source line a finger line under the source line points to the column position of the error For example 10 int add int int Fave PT o ue see a 1506 166 S Definition of function add re
163. Accritical section that contains goto continue or break statements that transfer program flow outside of the critical section e A goto statement outside a critical section that transfers program flow to a label defined within a critical section A thread waits at the start of a critical region identified by a given name until no other thread in the program is executing a critical region with that same name Critical sections not specifically named by the ibm critical or omp critical directives are mapped to the same unspecified name Example pragma ibm critical int s a 100 i pragma ibm parallel loop for i 0 i lt 100 i pragma ibm critical lock1 s s alil i Related Reading 396 C for AIX User s Guide pragma omp barrier Preprocessor Directive The omp barrier directive identifies a synchronization point at which threads in a parallel region will wait until all other threads in that section reach the same point Statement execution past the omp barrier point then continues in parallel Syntax pragma omp barrier Notes The omp barrier directive must appear within a block or compound statement For example if x 0 pragma omp barrier valid usage if x 0 pragma omp barrier invalid usage Related Reading pragma omp atomic Preprocessor Directive The omp atomic directive identifies a specific memory location that must be updated atomically and not be expose
164. C for AIX User s Guide all C for AIX User s Guide all Note Before using this information and the product it supports be sure to read the general information aoe September 1999 Edition This documentation applies to Version 5 Release 0 of the C for AIX compiler and to all subsequent releases and modifications until otherwise indicated in new editions Make sure you are using the correct edition for the level of the product Order publications through your IBM representative or the IBM branch office serving your locality Publications are not stocked at the address below If you have comments about this document address them to IBM Canada Ltd Laboratory Information Development 2G 345 1150 TOR 1150 Eglinton Avenue East North York Ontario Canada M3C 1H7 When you send information to IBM you grant IBM a nonexclusive right to use or distribute the information in any way it believes appropriate without incurring any obligation to you Copyright International Business Machines Corporation 1995 1999 All rights reserved US Government Users Restricted Rights Use duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp iV C for AIX User s Guide Contents Notices Trademarks and Senie Marks About this Information Related Reading IBM Publications Non IBM Publications Chapter 1 Introducing C for AIX Chapter 2 Setting Up the C for AIX Compilation Environment Set
165. C for AIX compiler Executable File By default executable files are named a out To name the executable file something else use the ofile_name option with the invocation command This option creates an executable file with the name you specify as file_name The name you specify can be a relative or absolute path name for the executable file The format of the a out file is described in the AlX Version 4 Files Reference Object Files Object files must have an o suffix for example year o unless the ofilename option is specified If you specify the c option an output object file file_name o is produced for each input source file file_name c The linkage editor is not invoked and the object files are placed in your current directory All processing stops at the completion of the compilation You can link edit the object files later into a single executable file using the xlec command Assembler Files Assembler files must have an s suffix for example check s They are created by specifying the S option Assembler files are assembled to create an object file Preprocessed Source Preprocessed source files have an isuffix for example tax_calc i Files To make a preprocessed source file specify the P option The source files are preprocessed but not compiled A preprocessed source file file_name i is produced for each source file file_name c Listing Files Listing files have an Ist suffix for example form st Specifyi
166. Chunks are assigned to threads on a first come first serve basis as threads become available This continues until all work is completed Scheduling policy is determined at run time Use the OMP_SCHEDULE environment variable to set the scheduling type and chunk size Iterations of a loop are divided into chunks of size ceiling number_of_iterations number_of_threads Each thread is assigned a separate chunk This scheduling policy is also known as block scheduling lterations of a loop are divided into chunks of size n Each chunk is assigned to a thread in round robin fashion n must be an integral assignment expression of value 1 or greater This scheduling policy is also known as block cyclic scheduling lterations of a loop are divided into chunks of size 1 Each chunk is assigned to a thread in round robin fashion This scheduling policy is also Known as cyclic scheduling Appendix E Parallel Processing Facilities 391 nowait Use this clause to avoid the implied barrier at the end of the for directive This is useful if you have multiple independent work sharing sections or iterative loops within a given parallel region Only one nowait clause can appear on a given for directive and where for_loop is a for loop construct with the following canonical shape for init_expr exit_cond incr_expr statement where init_expr takes form Tei integer type iv b exit_cond takes form TE iv lt ub iv gt ub iv gt ub
167. Compilation conforms to the SAA C Level 2 CPI language level definition with some exceptions SAA Compilation conforms to the current SAA C CPI language level definition This is currently SAA C Level 2 EXTended Provides compatibility with the RT compiler and classic language levels CLAssic Allows the compilation of non ANSI language level programs and conforms closely to the K amp R level preprocessor NOUCS The default is NOUCS This suboption can be used together with other qlanglvl suboptions UCS With option qlanglvl ucs you can use universal character names in form of unnnn or Unnnnnnnn as defined in the C9X Final Draft International Standard ISO IEC 9899 1999 The universal character name unnnn designates a character whose four digit short identifier is nnnn The universal character name Unnnnnnnn designates a character whose eight digit short identifier is nnnnnnnn Short identifiers of characters are specified by ISO IEC 10646 A four digit identifier of nnnn is identical to an eight digit short identifier of O00Onnnn Universal character names may be used in identifiers character constants and string literals to designate characters that are not in the basic character set A universal character name shall not specify a character whose short identifier is e less than OOAO except 0024 0040 and 0060 or e inthe range D800 through DFFF inclusive If more than one language level is specified the later opti
168. Compiler Configuration File Appendix M ASCII Character Set Appendix N Problem Solving Message Catalog Errors Correcting Page Space Errors During Compilation Appendix O Glossary NS lt CHAMNDVOZSEE A TOTMMOOO DW Contents 464 465 465 467 469 469 469 473 474 474 477 483 487 487 487 489 489 489 490 491 492 492 493 493 493 494 494 495 495 495 496 496 496 497 497 498 498 498 xiii XIV C for AIX User s Guide Notices Any reference to an IBM licensed program in this publication is not intended to state or imply that only IBM s licensed program may be used Any functionally equivalent product program or service that does not infringe any of IBM s intellectual property rights may be used instead of the IBM product program or service Evaluation and verification of operation in conjunction with other products except those expressly designated by IBM is the user s responsibility IBM may have patents or pending patent applications covering subject matter in this document The furnishing of this document does not give you any license to these patents You can send license inquiries in writing to Director of Licensing Intellectual Property amp Licensing International Business Machines Corporation North Castle Drive MD NC119 Armonk New York 10504 1785 U S A Licensees of this progr
169. Compiler Options 335 If you update your system header files you can regenerate them with the usr vac bin mkpcomp command Precompiled headers will only be used at the same language level used during their creation For a given include qusepcomp is checked first Then the compiler checks for a precompiled version of the file to be included if such is specified If it is found and it is current it is used If a precompiled header is not being used for example if a current one is not found or if qusepcomp is not specified and qgenpcomp is specified the compiler will create a new precompiled header even if it exists and is current The precompiled headers created by installing C for AIX are listed in the LPP inventory and are removed if you uninstall C for AIX Any additional headers you create are not removed during uninstall Related Reading Option Type Default Value pragma options e Syntax V Purpose Instructs the compiler to report information on the progress of the compilation and names the programs being invoked within the compiler and the options being specified to each program Information is displayed to standard output Notes The v option is overridden by the option Example To compile myprogram c so you can watch the progress of the compilation and see messages that describe the progress of the compilation the programs being invoked and the options being specified enter xlc myprogram c
170. D Preprocessor Directives and Related Information 351 printf value 2 d n b int main void int x 2 int y 3 PRNT SQR x sy s return 0 After being interpreted by the preprocessor this program is replaced by code equivalent to the following include lt stdio h gt int main void int x 2 int y 3 printf value 1 printf value 2 return 0 d n x x d n y This program produces the following output value 1 4 value 2 3 Related Reading if elif Preprocessor Directives The if and elif directives compare the value of the expression to zero i i T TE constant expression E sees ee elit If the constant expression evaluates to a nonzero value the tokens that immediately follow the condition are passed on to the compiler If the expression evaluates to zero and the conditional compilation directive contains a preprocessor elif directive the source text located between the elif and the next elif or else preprocessor directive is selected by the preprocessor to be passed on to the compiler The elif directive cannot appear after the preprocessor else directive All macros are expanded any defined expressions are processed and all remaining identifiers are replaced with the token 0 The expressions that are tested must be integer constant expressions with the following properties e No casts are performed e Arithmetic is performed using long int values e T
171. E KEKE RE REE KER KER ERERE Related Reading 414 C for AIX User s Guide _debug_memmove Copy Bytes Format include lt string h gt void debug _memmove void dest const void src size_t count const char file size t line Language Level Extension _debug_memmove is the debug version of memmove Like memmove it copies count bytes of src to dest and allows for copying between objects that may overlap _debug_memmove validates the heap after copying the bytes to the target location and performs this check only when the target is within a heap debug memmove makes an implicit call to heap check lf debug memmove detects a corrupted heap when it makes a call to heap_check _debug memmove will report the file name file and line number line in a message Note debug memmove checks only the current default heap Therefore this debug support will not check all heaps within applications that have multiple user heaps To use debug memmove you must compile with the debug memory qheapdebug compiler option This option maps all memcpy calls to debug memmove You do not have to change your source code in order for debug _memmove to verify the heap Note The qheapdebug option maps all calls to other string functions and all calls to memory management functions including a heap specific version to their debug counterparts To prevent a call from being mapped parenthesize the function name Return Value _debug_memmove re
172. ERK EKER KER ERR ERK Kk Kk Kk k The output should be similar to destination is originally abcdefg End of allocated object 0x00073c80 was overwritten at 0x00073c8a The first eight bytes of the memory block in hex are 3132333435363738 This memory block was re allocated at line number 14 in strncpy c 424 C for AIX User s Guide Heap state was valid at line 15 of strncpy c Memory error detected at line 18 of strncpy c KK KK KKK KKK KK RK RK kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkx Related Readin _debug_strnset Set Characters in String Format include lt string h gt char debug strnset char string int c size tn const char file size t line Language Level Extension _debug_strnset is the debug version of strnset Like strnset it sets at most the first n characters of string to c converted to a char where if n is greater than the length of string the length of string is used in place of n _debug_strnset validates the heap after setting the bytes and performs this check only when the target is within a heap _debug_strnset makes an implicit call to heap check If debug_strnset detects a corrupted heap when it makes a call to heap check debug _strnset will report the file name file and line number line in a message Note debug_strnset checks only the current default heap Therefore this debug support will not check all heaps within applications that have multiple user heap
173. First Name MI Street Address City Province Postal code char temp_string abc def ghi temp_string abcdefghi 0 wchar_t wide_string L longstring Escape Sequences You can represent any member of the execution character set by an escape sequence They are primarily used to put nonprintable characters in character and string literals For example you can use escape sequences to put such characters as tab carriage return and backspace into an output stream escape sequence character re a ASSOCI RSL digits _ ecie argiis Pe An escape sequence contains a backslash symbol followed by one of the escape sequence characters or an octal or hexadecimal number A hexadecimal escape sequence contains an x followed by one or more hexadecimal digits 0 9 A F a f An octal escape sequence uses up to three octal digits 0 7 The value of the hexadecimal or octal number specifies the value of the desired character or wide character Note The line continuation sequence followed by a new line character is not an escape sequence It is used in character strings to indicate that the current line continues on the next line The escape sequences and the characters they represent are Escape Sequence Character Represented a Alert bell alarm b Backspace f Form feed new page n New line 52 C for AIX User s Guide Wr Carriage return t Horizontal tab v Vertical tab Single quotation mark
174. For example struct S 4 short x 4 long y 10 char Z 7 S Non integral bit fields in extended mode C are converted to type unsigned int and a warning is issued In other modes the use of non integral bit fields results in an error In ansi mode C bit fields of type unsigned char or unsigned short are changed to unsigned int An unsigned short bit field occupies 32 bits A bit field cannot have the volatile or const qualifier The following structure has three bit field members kingdom phylum and genus occupying 12 6 and 2 bits respectively struct taxonomy int kingdom 12 int phylum 6 int genus 2 l Alignment of Bit Fields in Structures Bit fields are word aligned but packed as closely as possible into the current word The first bit field in a sequence of bit fields starts on a word boundary For example a structure containing only bit fields is word aligned but after the first bit field the bit fields themselves do not have to begin on word boundaries Word alignment is the default and is equivalent to setting the qalign power compiler option If a series of bit fields does not add up to the size of an int padding can take place The amount of padding is determined by the alignment characteristics of the members of the structure Bit fields cannot cross word boundaries but are forced to start at the next word boundary Alignment of structures is described in The following example declares the i
175. Guide KKK KKK KK KKK EK KERR KEK KERR EK RRR KKK KERR ER KEKE RK ER AEE KEE RRR RK EKER EKER KER kk kkk kkk pragma hdrfile fred pch include hl h include h2 h main BRK RR KKK KEK KERR KEKE RRR k RRR k K KER KERR k Kk K k k k k RRR RK KERR EKER ER ERK KKK KK KK KKK Kk In the following example only header hl h will be precompiled provided the qgenpcomp compiler option is specified and the precompiled output is written to the file fred pch To use the precompiled output in fred pch when compiling specify the qusepcomp compiler option KKK AK KK KKK KKK EK KERR ERK EK KERR KKK KERR KER KEKE RK EKER RRR ERK ER EER ER KERR ERERERER pragma hdrfile fred pch include h1 h pragma hdrstop include h2 h main Related Reading pragma hdrstop Preprocessor Directive The oragma hdrstop directive manually terminates the initial sequence of include directives being considered for precompilation Me pragma hdrstop td It has no effect if e The initial sequence of include directives has already ended e Neither the qgenpcomp or qusepcomp compiler options are specified e t does not appear in the primary source file Using precompiled header files can decrease compile time Using precompiled headers will not improve compile time performance in most applications without some organization of the headers included by each source file Some examples of pragma hdrfile dire
176. IX with Other Programming Languages 209 Interlanguage Calls Parameter Passing The RISC System 6000 linkage convention specifies the methods for parameter passing and whether return values are to be in FPRs GPRs or both The GPRs and FPRs available for argument passing are specified in two fixed lists R8 R10 and FP1 FP13 Prototyping affects how parameters are passed and whether widening occurs Nonprototyped functions In nonprototyped functions in the C language floating point arguments are widened to double and integral types are widened to int Prototyped functions No widening conversions occur except in arguments passed to an ellipsis function Floating point double arguments are only passed in FPRs If an ellipsis is present in the prototype floating point double arguments are passed in both FPRs and GPRs When there are more argument words than available parameter GPRs and FPRs the remaining words are passed in storage on the stack The values in storage are the same as if they were in registers Space for more than 8 words of arguments float and nonfloat must be reserved on the stack even if all the arguments were passed in registers The size of the parameter area is sufficient to contain all the arguments passed on any call statement from a procedure associated with the stack frame Although not all the arguments for a particular call actually appear in storage they can be regarded as forming a list in this area each one oc
177. IZE 20 define EXIT FAILURE 999 int main void static char names Jim Amy Mark Sue NULL char find name char char char new_name SIZE name_pointer printf Enter name to be searched n scanf s new_name name pointer find _name names new_name printf name s sfound n new_name name pointer NULL not exit EXIT_FAILURE End of main KEK RE k k k KK RRR RRR ERE RRR ER KERR ERK ER ERR KERR KERR ER KER ERE k Kk KK KK kK k xx Function find_name This function searches an array we xx of names to see if a given name already exists in the xx array It returns a pointer to the name or NULL if xx the name is not found kx k k xx char arry is a pointer to arrays of pointers whose kx xx names already exist k k kxk xx char strng is a pointer to character array entered KA KKK KKK KKK KKK EK KERR KK ERR KERR KERR ERA K KERR ERK kk kkk Kk kk kkk kk kk char find name char arry char strng for arry NULL arry for each name if stremp arry strng 0 if strings match return arry found it x return arry return the pointer End of find_name Interaction with this program could produce the following sessions Output Enter name to be searched Input Mark Output name Mark found Or Output Enter name to be searched _ Input Deborah Output name Deborah not found 94 C for AIX U
178. Initialize a one dimensional character array by specifying e A brace enclosed comma separated list of constants each of which can be contained in a character e A string constant Braces surrounding the constant are optional Initializing a string constant places the null character 0 at the end of the string if there is room or if the array dimensions are not specified Initializing a multidimensional array Initialize a multidimensional array by e Listing the values of all elements you want to initialize in the order that the compiler assigns the values The compiler assigns values by increasing the subscript of the last dimension fastest This form of a multidimensional array initialization looks like a one dimensional array initialization The following definition completely initializes the array month days Static month days 2 12 N 205 oly OU Si 30 oly oly 26 21 30 31 aks 29s Ole Oe Ole 20 Ila oh 20 Ble 30 21 e Using braces to group the values of the elements you want initialized You can put braces around each element or around any nesting level of elements The following definition contains two elements in the first dimension You can consider these elements as rows The initialization contains braces around each of these two elements Chapter 6 The C Language 87 static int month days 2 12 1 ol 28 31 30 31 30 31 31 30 31 30 31 J t Ole 29 3l 30 31l 30 31 314 30 3l 30 31 E e
179. MEMORY SIZE if uheap NULL check for success return 1 if failure return non zero perform operations on uheap for i 1 i lt 5 i p _umalloc uheap 10 allocate from uheap if p NULL return 1 memset p M msize p set all bytes in p to M p realloc p 50 reallocate from uheap if p NULL return 1 memset p R _msize p set all bytes in p to R Start a second process which accesses the heap if system memshr2 exe return 1 Take a look at the memory that we just wrote to Note that memshr c and memshr2 c should have been compiled specifying the Tm flag ifdef DEBUG _udump_allocated uheap 1 endi f call term function to close and destroy the heap rc termhp uheap ifdef DEBUG printf memshr ending rc d n rc endif return re Example of a Shared User Heap Child Process Example of a Shared User Heap Child Process shows the process started by the loop in the parent process This process uses OpenFileMapping to access the shared memory by name then extracts the heap handle for the heap created by the parent process The process then opens the heap makes it the default heap and performs some operations on it in the loop After the loop the process replaces the old default heap closes the user heap and ends include lt umalloc h gt include lt stdio h gt include lt stdlib h g
180. SI C standard and is technically equivalent to ANSI X3 159 1989 e ISO IEC 9899 1990 E Presents the International Standards Organization ISO standard for the C language e Federal Information Processing Standards Publication C FIPS PUB 160 Presents the Federal Information Processing Standard FIPS for the C language XVii C for AIX User s Guide Chapter 1 Introducing C for AIX The C for AIX product is an IBM licensed program that operates in the AIX Version 4 Operating System environment Features of the C for AIX product include e Ability to compile in either 64 or 32 bit modes Programs compiled in 64 bit mode can only be run on 64 bit CPUs using AIX 4 3 or higher Programs compiled in 32 bit mode can be run on either 64 or 32 bit CPUs using AIX 4 2 or higher e Programming support for parallel processing architectures SMP automatic and explicit parallelization support OpenMP Application Program Interface support e Conformance to the following industry standards for compiling C language source code The Federal Information Processing Standard FIPS PUB 160 C language The American National Standard for Information Systems ANSI and International Standards Organization ISO standard ANSI ISO IEC 9899 1990 1992 for the C programming language The International Standards Organization ISO standard ISO IEC 9899 1990 E for the C programming language Conformance to IBM Systems Application Archite
181. The compiler truncates a Pascal string literal that is longer than 255 bytes excluding the length byte and the terminating NULL to 255 characters e The compiler ignores the qmacpstr option if qmbcs or qdbcs is used and issues a warning message e Because there is no Pascal string literal processing of wide strings using the escape sequence p in a wide string literal with the qmacpstr option generates a warning message and the escape sequence is ignored e The Pascal string literal is not a basic type different from other C string literals After the processing of the Pascal string literal is complete the resulting string is treated the same as all other strings If the program passes a C string to a function that expects a Pascal string or vice versa the behavior is undefined e Concatenating two Pascal string literals for example strcat does not result in a Pascal string literal However as described above two adjacent Pascal string literals can be concatenated to form one Pascal string literal in which the first byte is the length of the new string literal e Modifying any byte of the Pascal string literal after the processing has been completed does not alter the original length value in the first byte e No errors or warnings are issued when the bytes of the processed Pascal string literal are modified e Entering the characters p Pee B H A 0 into a character array does not form a Pascal string literal
182. To compile myprogram c so that range checking occurs and multiply add instructions are not generated enter xlc myprogram c qfloat fltint nomaf Related Reading flttrap Option Type Default Value pragma options Syntax qflttrap qflttrap suboptions qnoflttrap FLTTRAP FLTTRAP suboptions NOFLTTRAP Purpose Generates extra instructions to detect and trap floating point exceptions 264 _ for AIX User s Guide Notes This option is recognized during linking qnoflttrap specifies that these extra instructions need not be generated If specified with pragma options the qnoflttrap option must be the first option specified The flttrap option has the following suboptions OVerflow Generates code to detect and trap floating point overflow UNDerf1 ow Generates code to detect and trap floating point underflow ZEROdivide Generates code to detect and trap floating point division by zero INValid Generates code to detect and trap floating point invalid operation exceptions INEXact Generates code to detect and trap floating point inexact exceptions ENable Enables the specified exceptions in the prologue of the main program This suboption is required if you want to turn on exception trapping without modifying the source code IMPrecise Generates code for imprecise detection of the specified exceptions If an exception occurs it is detected but the exact location of the exception is not determined Specifying
183. Type specifier not required when a name that was previously defined as a typedef is redefined e and operators e ifdef using logical operators or period e Taking the address of a register variable e Function declarations at file scope without type specifiers e Variable declarations without type specifiers e Structure definition containing an empty structure declaration e Predefined macro names unix and AIX Chapter 6 The C Language 163 Related Reading Extensions to RT C Provided by extended C The following are part of the ANSI ISO C definition and are part of the extended language level They cause no conflict with existing RT C source e pragma elif and error preprocessor directives e Ability to form macro literals using e Macro concatenation using e Recursive macro definitions are only expanded once e White space or comment allowed before e Trigraph sequences e Redeclaration of typedef names variable defined as a typedef can be redeclared as an identifier e const and volatile type qualifiers e Support of the signed keyword with char int short and long data types e Suffixes 1 and L for type long double floating point constants e Suffixes u and U for types unsigned char and unsigned int e Hexadecimal constants of the form Oxdd e Unary operator e enum and void types e Function prototypes including variable number of arguments specified by an ellipsis e Init
184. Type specifiers indicate the type of object or function being created The basic ee of are You can use the basic a listed above to derive the following additional object types 66 C for AIX User s Guide The integral types are char and int of all sizes Floating point numbers can have types float double or long double Integral and floating point types are collectively called arithmetic types You can give names to both basic and derived types with the typedef specifier Related Reading Expressions and Operators Expressions are sequences of operators operands and punctuators that specify a computation The evaluation of an expressions is based on the operators that the expression contains and the context in which the operators are used Related Reading Operator Precedence and Associativity Two characteristics of operators determine how they will group with operands precedence Precedence is the priority for grouping different types of operators with their operands associativity Associativity is the left to right or right to left order for grouping operands to operators that have the same precedence For example in the following statements the value of 5 is assigned to both a and b because of the right to left associativity of the operator The value of c is assigned to b first and then the value of b is assigned to a Chapter 6 The C Language 67 3 e 3 II O oO wo C3 Because t
185. U1 7 J F 2K j The value k and not k j is treated as the third operand This error arrises because a conditional expression is not an lvalue and the assignment is not valid To make the expression evaluate correctly enclose the last operand in parenetheses For example int is Ja Ki i 7 j k j Related Reading Assignment Operators Chapter 6 The C Language 133 Simple Assignment The simple assignment operator stores the value of the right operand in the object designated by the left operand Both operands must have arithmetic types the same structure type or the same union type Otherwise both operands must be pointers to the same type or the left operand must be a pointer and the right operand must be the constant O or NULL If the language level is extended both operands can be pointers to different types If both operands have arithmetic types the system converts the type of the right operand to the type of the left operand before the assignment If the left operand is a pointer and the right operand is the constant 0 the result is NULL Pointers to void can appear on either side of the simple assignment operator A packed structure or union can be assigned to a nonpacked structure or union of the same type and a nonpacked structure or union can be assigned to a packed structure or union of the same type If one operand is packed and the other is not the layout of the right operand is remappe
186. UM_THREADS environment variable 400 C for AIX User s Guide int omp get num threads void This function returns the number of threads currently in the team executing the parallel region from which it is called int omp_get_max threads void This function returns the maximum value that can be returned by calls to omp_get_num_threads int omp_get_thread_num void This function returns the thread number within its team of the thread executing the function The thread number lies between 0 and omp_get_num_threads 1 inclusive The master thread of the team is thread 0 int omp_get_num procs void This function returns the maximum number of processors that could be assigned to the program int omp_in_parallel void This function returns non zero if it iS called within the dynamic extent of a parallel region executing in parallel otherwise it returns 0 void omp_set_dynamic int dynamic threads This function enables or disables dynamic adjustment of the number of threads available for execution of parallel regions int omp_get_dynamic void This function returns non zero if dynamic thread adjustments enabled and returns 0 otherwise void omp_set_nested int nested This function enables or disables nested parallelism int omp_get_nested void This function returns non zero if nested parallelism is enabled and 0 if it is disabled void omp_init_lock omp_lock t lock These functions provide the only means
187. Using use nested braces to initialize dimensions and elements in a dimension selectively Related Reading AAMOIC Q La cA CALG Array Subscript page RE Examples of Array Declaration and Use The following show four different character array initializations static char namel Ju a m E static char name2 Jan static char name3 3 Jan static char name4 4 Jan These initializations create the following elements named mame ames Element Value Element vate Element Element Oa co me n s m w ef E Note that the NULL character O is lost for namel and name3 3 A compiler warning is issued for name3 3 namel 1 Poa name2 1 The following program defines a floating point array called prices The first for statement prints the values of the elements of prices The second for statement adds five percent to the value of each element of prices and assigns the result to total and prints the value of total xx Example of one dimensional arrays XAJ include lt stdio h gt define ARR SIZE 5 int main void static float const prices ARR SIZE 1 41 1 50 3 75 5 00 86 auto float total int i for i 0 i lt ARR SIZE i printf price 2f n prices i printf n for i 0 i lt ARR_SIZE i total prices i 1 05 88 c for AIX User s Guide printf total 2f n total return 0 This program produces the
188. When the entire program has been preprocessed the result is scanned again by the compiler as in the first step The second and third steps do not apply here since there will be no macros to replace Constructs generated by the first three steps which resemble preprocessing directives are not processed as such lt is in the third and fourth steps that the text of adjacent but previously separate tokens may be combined to form new tokens The character for line continuation is accepted only in string literals and character constants and on preprocessing directives Constructs such as if 0 unterminated endif define US Unterminating string char s US terminated now will not generate diagnostic messages since the first is an unterminated literal in a FALSE block and the second is completed after macro expansion However char s US will generate a diagnostic message since the string literal in US is not completed before the end of the line Empty character literals are allowed The value of the literal is 0 Preprocessing directives The token must appear in the first column of the line The token immediately following is available for macro expansion The line can be continued with only if the name of the directive and in the following example the has been seen define f a b a b f 1 2 accepted define f a b a b fA 1 2 not accepted The rules concerning apply whether or not the directiv
189. YNAMIC TRUE FALSE This environment variable enables or disables dynamic adjustment of the number of threads Note Related available for running parallel regions If set to TRUE the number of threads available for executing parallel regions may be adjusted at runtime to make the best use a S ii resources See the description for profilefreq num in on page 402 for more information If set to FALSE dynamic adjustment is disabled The default setting is TRUE You must use thread safe compiler mode invocations when compiling parallelized program code Appendix E Parallel Processing Facilities 405 406 C for AIX User s Guide Appendix F C for AIX Debug Functions _debug_calloc Allocate and Initialize Memory Format include lt stdlib h gt also in lt malloc h gt void debug calloc size t num size t size const char file size t line Language Level Extension _debug _calloc is the debug version of calloc Like calloc it allocates memory from the default heap for an array of num elements each of length size bytes It then initializes all bits of each element to O In addition debug_calloc makes an implicit call to heap check and stores the name of the file file and the line number line where the storage is allocated This information can be used later by the _heap_check dump_allocated or dump_allocated_delta functions To use _debug calloc you must compile with the debug memory qheapdebu
190. You can use a different default heap for each thread of your program if you choose This is useful when you want a component such as a vendor library to use a heap other than the C for AIX runtime heap but you can t actually alter the source code to use heap specific calls For example if you set the default heap to a shared heap then call a library function that calls malloc the library allocates storage in shared memory Because _udefault returns the current default heap you can save the return value and later use it to restore the default heap you replaced You can also change the default back to the C for AIX runtime heap by calling _udefault and specifying _RUNTIME_HEAP defined in lt umalloc h gt You can also use this macro with any of the heap specific functions to explicitly allocate from the runtime heap Chapter 7 Writing C Programs 185 Related Reading Creating and Using a Fixed Size Heap Before creating a heap you must first allocate a block of memory large enough to hold the heap The block must be large enough to satisfy all the memory requests your program will make of it and also be able to hold internal information required to manage the heap Once the block is fully allocated further allocation requests to the heap will fail The internal information requires HEAP MIN SIZE bytes _HEAP_MIN SIZE is defined in lt umalloc h gt You cannot create a heap smaller than this Add the amount of memory your program
191. _declaration is ignored A case clause contains a case label followed by any number of statements ee case label eee eee A case label contains the word case followed by an integral constant expression and a colon Anywhere you can put one case label you can put multiple case labels pp case Hegel consent exeressign pg A default clause contains a default label followed by one or more statements You can put a case label on either side of the default label A switch statement can have only one default label be dete JE zcte inert cese_lebe cese_lebe Chapter 6 The C Language 155 The switch statement passes control to the statement following one of the labels or to the statement following the switch body The value of the expression that precedes the switch body determines which statement receives control This expression is called the switch expression The value of the switch expression is compared with the value of the expression in each case label If a matching value is found control is passed to the statement following the case label that contains the matching value If there is no matching value but there is a default label in the switch body control passes to the default labelled statement If no matching value is found and there is no default label anywhere in the switch body no part of the switch body is processed When control passes to a statement in the switch body control only leaves the switch body when
192. _expr expression is not within a critical section The following are examples of countable loops for Liv exit_cond incr_expr statement for Liv exit_cond expr declaration list statement list incr_expr statement list while exit_cond declaration list statement list incr expr statement_list do declaration list statement list incr_expr statement list while exit_cond The following definitions apply to the above examples 38 C for AIX User s Guide takes form Py ee Ub iv lt ub iv gt ub iv gt ub takes form EET v t iv iv iv incr iv incr iv iv incr iv incr iv iv iv incr exit_cond incr_expr Iteration variable The iteration variable is a signed integer that has either automatic or register storage class does not have its address taken and is not modified anywhere in the loop except in incr_expr Loop invariant signed integer expression The value of the expression is known at compile time and is not 0 incr cannot reference extern or static variables pointers or pointer expressions function calls or variables that have their address taken ub Loop invariant signed integer expression ub cannot reference extern or static variables pointers or pointer expressions function calls or variables that have their address taken LV incr Related Reading Reduction Operations in Parallelized Loops The compiler can recog
193. _jmpbuf jmp_context fpscr amp FP ALL XCP signal SIGTRAP fhandler_ Continue execution with the instruction following the trap Scp gt sc_jmpbuf jmp_context iar 4 Find and decode the floating point instruction causing the exception Return 1 if not found else zero static int find_instr unsigned int trap_loc Search backward in the instruction stream starting from trap_loc looking for a floating point instruction bits x 0 5 equal decimal 63 The first such instruction found will be assumed to be the failing operation Note that a linear backward search assumes that there is no branching code separating the trap instruction from x the failing floating point operation This will always be true with the current implementation of the flttrap x option in fact in the current implementation the failing operation will always be the second last x instruction before the trap point except in the case of subroutine calls causing an exception For safety we limit the search length int i 0 while trap_loc gt gt 26 63 amp amp i lt 10 if trap_loc gt gt 26 63 return 1 no float op found Check that the operation found has the record bit set if trap_loc amp 1 return 1 record bit not set Check to see if the instruction found was a move register This instruction is produced after calls to external
194. a break statement is encountered or the last statement in the switch body is processed If necessary an integral promotion is performed on the controlling expression and all expressions in the case statements are converted to the same type as the controlling expression Restrictions The switch expression and the case expressions must have an integral type The value of each case expression must represent a different value and must be a constant expression Only one default label can occur in each switch statement You cannot have duplicate case labels in a switch statement of the switch body but the compiler does not initialize variables at the beginning of a switch body The following gE Each clause contains a eian call and a Ebree page prevent control from passing down through each statemen in the switch body If the switch expression evaluates to the switch statement calls the function divide Control then passes to the statement following the switch body char key printf Enter an arithmetic operator n scanf c amp key switch key case add break case subtract break case multiply break case divide break 156 C for AIX User s Guide default printf invalid key n break If the switch expression matches a case expression the statements following the case expression are processed until a statement is encountered or the end of the body is reached
195. a function such as malloc Related Reading static on page 112 Storage Class Specifier Storage Class Specifier Name Spaces The compiler sets up name spaces to distinguish among identifiers referring to different kinds of entities Identical identifiers in different name spaces do not interfere with each other even if they are in the same scope You must assign unique names within each name space to avoid conflict The same identifier can be used to declare different objects as long as each identifier is unique within its name space The syntactic context of an identifier within a program lets the compiler resolve its name space without ambiguity Identifiers in the same name space can be redefined within enclosed program blocks as described in Within each of the following four name spaces the identifiers must be unique e Tags of these types must be unique within a single scope Enumerations Structures and unions Chapter 6 The C Language 57 e Members of structures and unions must be unique within a single structure or union type e Statement labels have function scope and must be unique within a function e All other ordinary identifiers must be unique within a single scope Function names Variable names Names of function parameters Enumeration constants typedef names Related Reading Example of Name Space Separation Structure tags structure members variable nam
196. a omp for Preprocessor Directive The omp for directive instructs the compiler to distribute loop iterations within the team of threads that encounters this work sharing construct Syntax pragma omp for clause clause lt for_loop gt where clause is any of the following private list Declares the scope of the data variables in ist to be private to each thread Data variables in list are separated by commas firstprivate list Declares the scope of the data variables in ist to be private to each thread Each new private object is initialized as if there was an implied declaration within the statement block Data variables in list are separated by commas lastprivate list Declares the scope of the data variables in ist to be private to each thread The final value of each variable in ist if assigned will be the value assigned to that variable in the last iteration Variables not assigned a value will have an indeterminate value Data variables in list are separated by commas Appendix E Parallel Processing Facilities 389 reduction operator Performs a reduction on all scalar variables in ist using the specified operator Reduction list variables in list are separated by commas A private copy of each variable in list is created for each thread At the end of the statement block the final values of all private copies of the reduction variable are combined in a manner appropriate to the operator and the result is pl
197. able at each invocation of the block The register storage class specifier indicates that the object is heavily used and indicates to the compiler that the value of the object should reside in a machine register Because of the limited size and number of registers available on most systems few variables can actually be put in registers If the compiler does not allocate a machine register for a register object the object is treated as having the storage class specifier auto Using register definitions for variables that are heavily used may make your object files smaller and make them run faster In object code a reference to a register can require less code and time than a reference to memory In C programs even if a register variable is treated as a variable with storage class auto the address of the variable cannot be taken Restrictions You cannot use the register storage class specifier in file scope data declarations You cannot apply the address amp operator to register variables Related Reading Block Scope Data Declarations static The static storage class specifier lets you define objects with static storage duration and internal linkage or to define functions with internal linkage An object having the static storage class specifier can be defined within a block or at file scope If the definition occurs within a block the object has no linkage If the definition occurs at file scope the object has internal link
198. ace For example pragma options langlvl ansi halt s spill 1024 source Most pragma options directives must come before any statements in your source program only comments blank lines and other pragma specifications can precede them For example the first few lines of your program can be a comment followed by the pragma options directive The following is an example of a pragma options directive pragma options langlvl ansi halt s spill 1024 source The rest of the source follows Options specified before any code in your source program apply to your entire program source code You can use other pragma directives throughout your program to turn an option on for a selected block of source code For example you can request that parts of your source code be included in your compiler listing pragma options source Source code between the source and nosource pragma options is included in the compiler listing x pragma options nosource Options specified in program source files override all other option settings 12 C for AIX User s Guide Related Reading Specifying Compiler Options in a Configuration File The default configuration file etc vac cfg specifies information that the compiler uses when you invoke it This file defines values used by the compiler to compile C programs You can make entries to this file to support specific compilation requirements or to support other C compilation environ
199. aced back into the original value of the shared reduction variable Variables specified in the reduction clause e must be of a type appropriate to the operator e must be shared in the enclosing context e must not be const qualified e must not have pointer type ordered Specify this clause if an ordered construct is present within the dynamic extent of the omp for directive 390 C for AIX User s Guide schedule type Specifies how iterations of the for loop are divided among available threads Acceptable values for type are dynamic dynamic guided guided n runtime static static n static 1 n If n is not specified iterations of a loop are divided into chunks of size ceiling number_of_iterations number_of_threads If n is specified all chunks are set to size n n must be an integral assignment expression of value 1 or greater Chunks are dynamically assigned to threads on a first come first serve basis as threads become available This continues until all work is completed Chunks are made progressively smaller until the default minimum chunk size is reached The first chunk is of size ceiling number_of_iterations number_of_threads Remaining chunks are of size ceiling number_of_iterations_remaining number_of_threads If n is specified the minimum chunk size is set to n n must be an integral assignment expression of value 1 or greater If n is not specified a default value of 1 is assumed
200. achine configuration and the workload on the system setting the limit too high might lead to page space exhaustion In particular specifying qmaxmem 1 allows the compiler to try and use an infinite amount of storage which in the worst case can exhaust the resources of even the most well equipped machine Example To compile myprogram c so that the memory specified for local table is 4096 kilobytes enter xlc myprogram c qmaxmem 4096 300 C for AIX User s Guide Related Reading mbcs dbcs Option Type Default Value pragma options Syntax qmbcs qdbcs qnombcs qnodbcs MBCS DBCS NOMBCS NODBCS Purpose Use the qmbcs option if your program contains multibyte characters The qmbcs option is equivalent to qdbcs Notes Multibyte characters are used in certain languages such as Japanese and Korean Example To compile myprogram c if it contains multibyte characters enter xlc myprogram c qmbcs Related Reading noprint Option Type Default Value pragma options a E Syntax qnoprint Purpose Suppresses listings qnoprint overrides all of the listing producing options regardless of where they are specified Notes The default is not to suppress listings if they are requested The options that produce listings are e qattr e qlist e qlistopt e qsource e qxref Appendix A Compiler Options 301 Example To compile myprogram c and suppress all listings even if some files have
201. age Initialization You can initialize any static object with a constant expression or an expression that reduces to the 112 C for AIX User s Guide address of a previously declared extern or static object possibly modified by a constant expression If you do not provide an initial value the object receives the value of zero of the appropriate type Storage Storage is allocated at compile time for static variables that are initialized Uninitialized static variables are mapped at compile time and initialized to 0 zero at load time This storage is freed when the program finishes running Beyond this the language does not define the order of initialization of objects from different files Block Scope Usage Use static variables to declare objects that retain their value from one execution of a block to the next execution of that block The static storage class specifier keeps the variable from being reinitialized each time the block where the variable is defined runs For example Static float rate 10 5 Initialization of a static array is performed only once at compile time The following examples show the initialization of an array of characters and an array of integers static char message static int integers startup completed I va J3 4 5s 6 ls 9 9 10 ps File Scope Usage The static storage class specifier causes the variable to be visible only in the file where it is declared Files therefore cannot acces
202. age Placing constant values in read only memory can improve runtime performance save storage and provide shared access Code that attempts to modify a read only constant value generates a memory error Constant value in the context of the qroconst option refers to variables that are qualified by const including const qualified characters integers floats enumerations structures unions and arrays The following variables do not apply to this option e variables qualified with volatile and aggregates such as a struct or a union that contain volatile variables e pointers and complex aggregates containing pointer members e automatic and static types with block scope e uninitialized types e regular structures with all members qualified by const e jnitializers that are addresses or initializers that are cast to non address values The qroconst option does not imply the qro option Both options must be specified if you wish to specify storage characteristics of both string literals qro and constant values qroconst Related Reading rm Option Type Default Value pragma options Syntax qrrm qnorrm RRM NORRM Purpose Prevents floating point optimizations that are incompatible with run time rounding to plus and minus infinity modes Notes This option informs the compiler that at run time the floating point rounding mode may change or that the mode is not set to yn rounding to the nearest representable num
203. agma options directive must be specified before the first statement in the compilation unit The qcheck option affects the runtime performance of the application When checking is enabled runtime checks are inserted into the application which may result in slower execution Example For qcheck null bounds void funcl int p xp 42 Traps if p is a null pointer void func2 int i int array 10 array i 42 Traps if i is outside range 0 9 For qcheck divzero void func3 int a int b a b Traps if b 0 Related Reading compact Option Type Default Value pragma options Syntax qcompact qnocompact COMPACT NOCOMPACT Purpose When used with optimization reduces code size where possible at the expense of execution speed Notes Code size is reduced by inhibiting optimizations that replicate or expand code inline Execution time may increase 246 C for AIX User s Guide Example To compile myprogram c to reduce code size enter xlc myprogram c qcompact Related Reading cpluscmt Option Type Default Value pragma options Syntax qcpluscmt qnocpluscmt CPLUSCMT NOCPLUSCMT Purpose Use this option if you want C comments to be recognized in C source files Notes The pragma options directive must appear before the first statement in the C language source file and applies to the entire file C comments have the form text The two slashes in the c
204. ain pragmas qopt noinfo Produces informational messages Appendix A Compiler Options 221 qopt noinitauto Initializes automatic storage to the two digit hexadecimal byte value hex_value qopt noiniglue Generates fast external linkage by inlining the pointer glue code necessary to make a call to an external function or a call through a function pointer qopt See inline on page 277 Attempts to inline functions instead of generating calls to a function object compile time Turns on or customizes a noipa link time class of optimizations known as interprocedural analysis IPA qopt Specifies functions in the source file that have no side effects qopt flag Searches the specified directory for library files specified by the l option searches a specified library for linking qopt langlvl ansi Selects the C language level for compilation flag qopt noldbl128 Increases the size of long double type from 64 bits to 128 bits qopt nolibansi Assumes that all functions with the name of an ANSI C library function are in fact the system functions qopt nolinedebug Generates abbreviated line number and source file name information for the debugger qopt nolist Produces a compiler listing that includes an object listing qopt nolistopt Produces a compiler listing that displays all options in effect qopt nolonglit Changes implicit type selection in 64 bit mode to us
205. al variable a The argument to that_function has the value 6 int a this_function int Assumed to have no side effects pragma isolated_call this_function that_function a 6 this function 7 Call does not change the value of a other_function a Argument a has the value of 6 x 372 C for AIX User s Guide Related Reading pragma langlvl Preprocessor Directive The pragma langlvl directive selects the C language level used for compilation Pe pragma langll ansi cassie extended 55A zaal This pragma must appear before any statements in a source file The compiler uses predefined macros in the header files to make declarations and definitions available that define the specified language level Language levels available with the C for AIX compiler are Language Level Description Defines the predefined macros _ANSI__ and STDC _ and defines other langlvl variables The default language level for the clc and c89 compiler invocations is ansi Defines the predefined macro _CLASSIC__ and undefines other langlvl variables Defines the predefined macro _ EXTENDED _ and undefines other langlvl variables The default language level for the CC compiler invocation commands is extended Defines the predefined macro _ SAA _ and undefines other langlvl variables Defines the predefined macro _ SAA _L2__ and undefines other langlvl variables This pragma has the same effect as
206. alar type You can optionally specify an else clause on the if statement If the test expression evaluates to 0 and an else clause exists the statement associated with the else clause runs If the test expression evaluates to a nonzero value the statement following the expression runs and the else clause is ignored p if exeressian j a lse statement z When if statements are nested and else clauses are present a given else is associated with the closest preceding if statement within the same block Related Reading Examples Using the if else Statement The following example causes grade to receive the value A if the value of score is greater than or equal to 90 if score gt 90 grade A The following example displays Number is positive if the value of number is greater than or equal to O If the value of number is less than 0 it displays Number is negative if number gt 0 printf Number is positive n else printf Number is negative n The following example shows a nested if statement if paygrade 7 if level gt 0 amp amp level lt 8 Salary 1 05 152 C for AIX Users Guide else Salary 1 04 else Salary 1 06 The following example shows a nested if statement that does not have an else clause Because an else clause always associates with the closest if statement braces might be needed to force a particular else clause to associate with the correct if st
207. alent so that any mention of one in this book implies the other This is also true for the cc cc_r and cc128 commands Related Reading Compiler Modes There are several forms of the C for AIX compiler command to support various version levels of the C language Normally you should use the xle command for compiling your source files You can however use other forms of the command if your particular environment and file systems require it The basic compiler invocations are Invokes the compiler for C source files with a default language level of ansi and specifies compiler option qansialias to allow type based aliasing Use this invocation for new C programs Invokes the compiler for C source files with a default language level of extended and compler options qnoro and qnoroconst to provide compatibility with the RT compiler and placement of string literals or constant values in read write storage Use this invocation for legacy C code that does not require compliance withANSI C c89 Invokes the compiler for C source files with a default language level of ansi and specifies compiler options qansialias to allow type based aliasing and qnolonglong disabling use of long long and sets D_ANSI_C_SOURCE for ANSI conformant headers Use this invocation for strict conformance to the ANSI standard xic cC Copyright IBM Corp 1995 1999 5 C for AIX provides variations on the four basic compiler invocations These var
208. alloc did not detect that a memory block was overwritten return 0 Copyright IBM Corp 1995 1999 407 BRK kk kk KKK KERR k k k k k k K k ER KERR K k K ERK ER KR RRR KEKE EKER EKER KER AER k kk kk KK k kk Kk k k k The output should be similar to End of allocated object 0x00073890 was overwritten at 0x000738f4 The first eight bytes of the memory block in hex are 6161616161616161 This memory block was re allocated at line number 9 in _debug_callo c Heap state was valid at line 9 of _debug_callo c Memory error detected at line 14 of _debug_callo c KK KK K K K A k K K K K KK kK EK KER KK k KK KK KK k Kk KK K Kk Kk Kk K Kk Kk KR k Kk kk Kk k kk kk kkk kk kkk kkk kkk Related Reading _debug_free Free Allocated Memory Format include lt stdlib h gt also in lt malloc h gt void debug free void ptr const char file size t line Language Level Extension _debug_free is the debug version of free Like free it frees the block of memory pointed to by ptr _debug_free also sets each block of freed memory to 0xFB so you can easily locate instances where your program uses the data in freed memory In addition debug free makes an implicit call to the _heap_check and stores the file name file and the line number line where the memory is freed This information can be used later by the _heap_check _dump_allocated or dump_allocated_delta functions To use _debug free you must compile with the debug memory
209. ally application performance is optimized if you request optimization O option and compiler performance is optimized if you do not request optimization The C for AIX _inline Inline and __ inline language keywords override all Q options except Q The compiler will try to inline functions marked with these keywords regardless of other Q option settings To maximize inlining specify optimization O and also specify the appropriate Q option as described below Q Attempts to inline all appropriate functions with 20 executable source statements or fewer subject to the setting of any of the suboptions to the Q option If Q is specified last all functions are inlined Q Does not inline any functions If Q is specified last no functions are inlined 314 C for AIX User s Guide Q threshold Q names Q names Default Sets a size limit on the functions to be inlined The number of executable statements must be less than or equal to threshold for the function to be inlined threshold must be a positive integer The default value is 20 Specifying a threshold value of 0 causes no functions to be inlined except those functions marked with the __inline Inline or _inline keywords The threshold value applies to logical C statements Declarations are not counted as you can see in the example below increment int a b i for i 0 i lt l10 i statement 1 a i statement 2 b i statement
210. also supports arrays structures records unions and enumerations The C language contains a concise set of statements with functionality added through its library This division enables C to be both flexible and efficient An additional benefit is that the language is highly consistent across different systems The C library contains functions for input and output mathematics exception handling string and character manipulation dynamic memory management as well as date and time manipulation Use of this library helps to maintain program portability because the underlying implementation details for the various operations need not concern the programmer All of the standard C library functions and many others are part of the AIX Base Operating System BOS Runtime Services The AlX Version 4 Technical Reference Volumes 1 and 2 Base Operating System and Extensions describes all of the C library functions supported by the C for AIX compiler Refer to Subroutines Overview in AIX Version 4 System User s Guide Operating System and Devices for general information about library functions Lexical Elements of C Tokens Source code is treated during preprocessing and compilation as a sequence of tokens There are five different types of tokens e Identifiers e Keywords e Literals e Operators e Other separators Adjacent identifiers keywords and literals must be separated with white space Other tokens should be separated by
211. am who wish to have information about it for the purpose of enabling i the exchange of information between independently created programs and other programs including this one and ii the mutual use of the information which has been exchanged should contact IBM Canada Ltd Department 071 1150 Eglinton Avenue East North York Ontario M3C 1H7 Canada Such information may be available subject to appropriate terms and conditions including in some cases payment of a fee This publication may contain examples of data and reports used in daily business operations To illustrate them as completely as possible the examples may include the names of individuals companies brands and products All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental IBM may change this publication the product described herein or both Trademarks and Service Marks The following terms are trademarks of the International Business Machines Corporation in the United States and or other countries AIX AlXwindows C Set IBM OS 2 POWER POWER2 PowerPC RS 6000 Windows is a trademark or registered trademark of Microsoft Corporation in the U S and or other countries UNIX is a registered trademark in the U S and other countries licensed exclusively through X Open Company Limited Other company product and service names which may be denoted by a double asterisk
212. ample batch process might be evaluated last causing the second and third arguments to be passed with the same value In the following example main passes func two values 5 and 7 The function func receives copies of these values and accesses them by the identifiers a and b The function func changes the value of a When control passes back to main the actual values of x and y are not changed The called function func only receives copies of x and y and not the actual values themselves include lt stdio h gt int main void int x 5 y 7 func x y printf In main x d y void func int a int b a t b printf In func a d b sdn x y 3 d n a b Chapter 6 The C Language 73 This program produces the following output i bez l y In func a In main x Related Reading Implicit Type Conversions Integral Promotions Certain fundamental types can be used wherever an integer can be used The fundamental types that can be converted through integral promotion are e char short int e enumerators e objects of enumeration type e integer bit fields both signed and unsigned If the value cannot be represented by an int the value is converted to an unsigned int Note Integral promotions are not performed on longor long long integers Related Reading Standard Type Conversions Many C operators cause implicit tyoe conversions which change the type of a value When you
213. an potentially change the semantics of a program Reference to these compiler option must appear after the O3 option e The O3 compiler option implies qnostrict_induction unless qstrict_induction is explicitly specified 04 qOPTimize 4 This option is the same as O3 except that it also e Sets the qipa option e Sets the qarch and qtune options to the architecture of the compiling machine Note Later settings of O qcache qipa qarch and qtune options will override the settings implied by the O4 option 05 qOPTimize 5 This option is the same as O4 except that it e Sets the qipa level 2 option to perform full interprocedural data flow and alias analysis Note Later settings of O qcache qipa qarch and qtune options will override the settings implied by the O5 option Example To compile myprogram c for maximum optimization enter xlc myprogram c 03 For an in depth discussion of how to optimize and tune your programs refer to the Optimization and Tuning Guide for Fortran C and C Related Reading Option Type Default Value pragma options a Syntax Appendix A Compiler Options 305 o file spec Purpose Specifies an output location for the object assembler or executable files created by the compiler When the o option is used during compiler invocation file_spec can be the name of either a file or a directory When the o option is used during direct linkage editor invocation file_s
214. and Fortran together by calling each other or sharing files Such applications are among the early candidates for porting to 64 bit platforms for its abilities to solve larger mathematical models Experience shows that it is easier to modify data sizes types on the C side than the Fortran side of such applications The following table lists the equivalent Fortran type in the different modes TAT e signed long INTEGER INTEGER 8 unsigned long LOGICAL LOGICAL 8 A user must not mix XCOFF object formats from different modes A 32 bit Fortran XCOFF cannot mix with a 64 bit C or C XCOFF object and vice versa Since Fortran77 usually does not have an explicit pointer type it is common practice to use INTEGER variables to hold C or C pointers in 32 bit mode In 64 bit mode the user should use INTEGER 8 in Fortran Fortran90 does have a pointer but it is unsuitable for conversion to the basic C and C types In 64 bit mode Fortran will have a POINTER 8 that is 8 bytes in length as compared to their POINTER which is 4 bytes in length Related Reading 344 C forAIX User s Guide Appendix C Operating System Migration Considerations You should be aware of the following considerations when moving programs to AIX 4 3 time_t has changed type from AIX 4 2 to AIX 4 3 Library functions which take an argument of time_t or return type time_t may find type mismatches with your existing code in 32 bit mode time_t is changed from long typ
215. and Other Levels extended level C the default language level for the cc compiler invocation command adheres to the ANSI ISO C definition except where adherence conflicts with compatibility with the RT C implementation In the case of certain obsolete RT C language definitions adherence to the ANSI ISO C standard takes precedence over compatibility with RT C This page lists the conflicts between e extended C and ansi C page ked e extended C and RT C page ked Conflicts Between extended C and ansi C The following are areas where extended level C supports RT C constructs and conventions not supported by ansi level C e Macro expansion within quoted strings either single or double quotation marks Macro parameters found within quoted strings in replacement text are not replaced in ansi mode but are replaced in extended mode e Arithmetic conversions for example integral promotions extended level C follows the rules outlined in which differ from the ansi level C conversion rules defined in section 3 2 1 5 of the ANSI ISO C Standard e Scope of external functions declared at block scope In ansi mode external functions have block scope In extended mode they have file scope e Implicit pointer conversions extended mode allows assignment of a pointer to an object of a different type In ansi mode a cast operation is necessary if conversion is to be done e Pointers of different types can be assigned to each other In
216. and Pointers Using int and long types in expressions and assignments can lead to implicit conversion through promotions and demotions or explicit conversions through assignments and argument passing The following should be avoided e Using integer and long types interchangeably leading to truncation of significant digits or unexpected results e Passing long arguments to functions expecting type int e Exchanging pointers and int types causing segmentation faults e Passing pointers to a function expecting an int type resulting in truncation e Assignment of long types to float causing possible loss of accuracy Assigning a long constant to an integer will cause truncation without warning For example int i long 1 2147483648 INT_MAX 1 i l What will be the value of i INT_MAX 1 is 2147483647 1 0x80000000 which becomes INT_MIN when assigned into a signed type Truncation occurs because the highest bit is treated as a sign bit The rule here is that there will be a loss of significant digits Similar problems occur when passing constants directly to functions and in functions that return long types Making explicit use of the L and UL suffix will avoid most but not all problems Alternately you can avoid accidental conversions by using explicit prototyping Another good practice is to avoid implicit type conversion by using explicit type casting to change types 342 C for AIX User s Guide UndeclaredFunctions Any fun
217. and version of the compiler to the end of the generated object module date The compiler appends the date and time of compilation to the end of the generated object module timestamp The compiler appends the date and time of the last modification to the sourcer to the end of the generated object module copyright The compiler places text specified by the token_string into the generated object module This text loads into memory when the program runs user The compiler places text specified by the token_string into the generated object module This text does not load into memory when the program runs Related Reading pragma disjoint Preprocessor Directive The pragma disjoint directive lists the identifiers that are not aliased to each other within the scope of their use bP 4 orogmea disjoint l lt w ident fer where identifier is a primary expression that can be the name of an operator function conversion function destructor or a qualified name The directive informs the compiler that none of the identifiers listed shares the same physical storage which provides more opportunity for optimizations If any identifiers actually share physical storage the pragma may give incorrect results The pragma can appear anywhere in the source program that a declaration is allowed An identifier in the directive must be visible at the point in the program where the pragma appears The identifiers in the disjoint nam
218. anf d amp t_timer if t_timer lt 0 printf Timer was set to a negative value n else while count_down amp t_timer while timer not zero printf Timer has reached zero n printf Timer still counting d n t_timer End main lt pre gt ERK ERR k k k EKER k k k RRR RR ER RE K k K RRR KEKE KER ERK ERK RRR ERE k Kk KK EER REE RE xx This function decreases the value of timer by decrements xx Of 1 and returns false when the timer reaches zero kx KAAK KK KAk KK KK KAK KEK KER K KK kK KKK KK k Kk Kk KK kkk Kk KER KER kk Kk kkk kk kkk kkk int count_down int timer receives a copy of a pointer to t_timer return timer modifying t_timer in main End count_down Interaction with this program could produce the following sessions Chapter 6 The C Language 93 Output Set timer to _ Input 6 Output Timer still counting Timer still counting Timer still counting Timer still counting Timer still counting Timer has reached zero e N Ww A The following program contains pointer arrays EEk kkk kk kk kk k kk kk k kk kk kk k kkk kkk kkk kk Kk KEK Kk KKK EKK KK RRR KRKK ERE xx Program to search for the first occurrence of a specified xx character string in an array of character strings kx KEAK K KE KKK KEK KEK KERR ERK EKER KERR KERR ER KERR KRKK ERE k kkk kk kk kkk include lt stdio h gt include lt stdlib h gt include lt string h gt define S
219. arallel region except for work sharing constructs Work within work sharing constructs is distributed among the threads in a team Syntax pragma omp parallel clause clause lt statement_block gt where clause is any of the following if exp When the if argument is specified the program code executes in parallel only if the scalar expression represented by exp evaluates to a non zero value at run time Only one if clause can be specified private list Declares the scope of the data variables in ist to be private to each thread Data variables in list are separated by commas firstprivate list Declares the scope of the data variables in ist to be private to each thread Each new private object is initialized with the value of the original variable as if there was an implied declaration within the statement block Data variables in ist are separated by commas shared list Declares the scope of the data variables in ist to be shared across all threads Data variables in list are separated by commas copyin list For each data variable specified in ist the value of the data variable in the master thread is copied to the thread private copies at the beginning of the parallel region Data variables in list are separated by commas Each data variable specified in the copyin clause must be a threadprivate variable default shared none Defines the default data scope of variables in each thread Only one default clause ca
220. ared between a parent and several child processes Example of a Shared User Heap Parent Process shows the parent process which creates the shared heap First the main program calls the init function to allocate shared memory from the operating system using CreateFileMapping and name the memory so that other processes can use it by name The init function then creates and opens the heap The loop in the main program performs operations on the heap and also starts other processes The program then calls the term function to close and destroy the heap include lt umalloc h gt include lt stdio h gt include lt stdlib h gt Chapter 7 Writing C Programs 191 include lt string h gt define PAGING FILE OxFFFFFFFF define MEMORY SIZE 65536 define BASE MEM VOID 0x01000000 static HANDLE hFile Handle to memory file Static void hMap Handle to allocated memory typedef struct mem_info void pBase Heap _t pHeap MEM_INFO_T Pee ee inithp Function to create and open the heap with a named shared memory object _ static Heap t inithp size t heap size MEM INFO _T info Info structure Allocate shared memory from the system by creating a shared memory pool basing it out of the system paging swapper file hFile CreateFileMapping HANDLE PAGING FILE PAGE _READWRITE 0 heap size sizeof Heap t MYNAME_SHAREMEM if hFile NULL return NULL
221. ares a pointer to a structure of type date as a parameter date ptr has the storage class specifier register Chapter 6 The C Language 143 set_date register struct date date ptr date ptr gt mon 12 date _ptr gt day 25 date ptr gt year 87 Related Reading main Function The function main can be declared with or without arguments that pass program parameters and environment settings to the program Although any name can be given to these parameters they are usually referred to as argc argv and envp argc Is the argument count It has type int and indicates how many arguments are entered on the command line argv Is the argument vector It is an array of pointers to char array objects These char objects are null terminated strings that are the program arguments passed to the program when it is invoked envp Is an optional environment pointer It is an array of pointers to char objects that are the environment variables available to the program These have the form name value The system determines the value of this parameter during program initialization before calling main Because you can use the function getenv to get the value of these pointers there is usually no need to declare this parameter The value of argc indicates the number of pointers in the array argv If a program name is available the first element in argv points to a character array that contains the program name or the invocation name of
222. args lt countable for while do loop gt Pragma directives must appear immediately before the section of code to which they apply For most parallel processing pragma directives this section of code must be a countable loop and the compiler will report an error if one is not found More than one parallel processing pragma directive can be applied to a countable loop For example pragma ibm independent_loop pragma ibm independent calls pragma ibm schedule static 5 lt countable for while do loop gt Some pragma directives are mutually exclusive of each other If mutually exclusive pragmas are specified for the same loop the pragma last specified applies to the loop In the example below the parallel_loop pragma directive is applied to the loop and the sequential_loop pragma directive is ignored pragma ibm sequential loop pragma ibm parallel_loop Other pragmas if specified repeatedly for a given loop have an additive effect For example pragma ibm permutation a b pragma ibm permutation c is equivalent to pragma ibm permutation a b c OpenMP Directives Syntax pragma omp pragma_name_and_args statement_block Pragma directives generally appear immediately before the section of code to which they apply The omp parallel directive is used to define the region of program code to be parallelized Other OpenMP directives define visibility of data variables in the defined parallel region and how work within th
223. ariable in ist if assigned will be the value assigned to that variable in the last section Variables not assigned a value will have an indeterminate value Data variables in list are separated by commas Appendix E Parallel Processing Facilities 393 reduction operator Performs a reduction on all scalar variables in ist using the specified operator Reduction list variables in list are separated by commas A private copy of each variable in listis created for each thread At the end of the statement block the final values of all private copies of the reduction variable are combined in a manner appropriate to the operator and the result is placed back into the original value of the shared reduction variable Variables specified in the reduction clause e must be of a type appropriate to the operator e must be shared in the enclosing context e must not be const qualified e must not have pointer type nowait Use this clause to avoid the implied barrier at the end of the sections directive This is useful if you have multiple independent work sharing sections within a given parallel region Only one nowait clause can appear on a given sections directive Notes The omp section directive is optional for the first program code segment inside the omp sections directive Following segments must be preceded by an omp section directive All omp section directives must appear within the lexical construct of the program source code segment
224. ars compiler option If it does not matter whether a char data object is signed or unsigned you can declare the object as having the data type char Otherwise explicitly declare the object as signed char or unsigned char When a char signed or unsigned is widened to an int its value is preserved The following example defines the identifier end_of string as a constant object of type char having the initial value 0 the null character Chapter 6 The C Language 79 const char end of string 0 The following example defines the unsigned char variable switches as having the initial value 3 unsigned char switches 3 The following example defines string pointer as a pointer to a character char string_ pointer The following example defines name as a pointer to a character After initialization name points to the first letter in the character string Johnny char name Johnny The following example defines a one dimensional array of pointers to characters The array has three elements Initially they are a pointer to the string Venus a pointer to Jupiter and a pointer to Saturn static char planets Venus Jupiter Saturn Related Reading float double Pp Specifier Description O Allocates 8 bytes of data storage in 32 bit mode or 16 bytes if the qldbl128 or qlongdouble option is in effect Notes 1 The amount of storage allocated for a float double or long double floating
225. at concatenates a wide string and a multibyte string is not permitted Assignment between wide characters and multibyte characters is not permitted Concatenating wide character strings and multibyte character strings is not permitted Related Reading Appendix K National Languages Support in the C for AIX Compiler 471 472 C for AIX User s Guide Appendix L C for AIX Files You can install the C for AIX as an optional software product of the AIX for RISC System 6000 Installing the compiler places the following files on your system C for AIX README file which contains important usr vac xlIC README C information not included in other documentation Read this file before you use the compiler for the first time Code generator usr vac exe x Ccode usr vac exe bolt Default message catalogs usr vac exe default_msg vacdmsg cat usr vac exe default_msg vacfe cat usr vac exe default_msg vacimsg cat usr vac exe default_msg vacsmsg cat C driver programs usr vac bin xlc usr vac bin xlc128 usr vac bin xlc_r ust vac bin cc usr vac bin cc1 28 usr vac bin cc_r usr vac bin cleanpdf usr vac bin replaceCSET usr vac bin resetpdf usr vac bin restoreCSET usr vac bin showpdf Precompiled header support usr vac lib compmalloc o Memory debug support usr vac lib libhm a usr vac lib libhm_r a usr vac lib libhmd a usr vac lib libhmd_r a usr vac lib libhu a usr vac lib lipbhu_r a usr vac include stdlib h
226. at region is shared and synchronized For example the following example defines a parallel region in which iterations of a for loop can run in parallel pragma omp parallel pragma omp for for i 0 i lt n i This example defines a parallel region in which two or more non iterative sections of program code can run in parallel pragma omp parallel region code here is executed by all threads pragma omp sections each section is executed once pragma omp section structured block_1 42 C for AIX User s Guide pragma omp section structured block_2 Related Reading Chapter 5 Program Parallelization 43 44 C for AIX Users Guide Chapter 6 The C Language C is a programming language designed for a wide variety of programming tasks It is used for system level code text processing graphics and in many other application areas The C language described in these pages is consistent with the Systems Application Architecture Common Programming Interface also known as the SAA C Level 2 interface and with the International Standard C ANSI ISO IEC 9899 1990 1992 This standard has officially replaced American National Standard for Information Systems Programming Language C X3 159 1989 X3 159 1989 and is technically equivalent to the ANSI C standard C supports several data types including characters integers floating point numbers and pointers each in a variety of forms In addition C
227. ate block HEAP MIN SIZE starting block BLOCK CLEAN memory not set to 0 _HEAP_REGULAR regular memory getmore fn function to expand heap release fn function to shrink heap Note You can use the same getmore_ fn and release fn for more than one heap as long as the heaps use the same type of memory and your functions are not written specifically for one heap 188 C for AIX User s Guide Expanding Your Heap When you call umalloc or a similar function for your heap _umal loc tries to allocate the memory from the initial block you provided to ucreate If not enough memory is there it then calls your getmore_ fn Your getmore_fn then gets more memory from the operating system and adds it to the heap It is up to you how you do this Your getmore_fn must have the following prototype void getmore fn Heap _t uh size t size int clean The uh is the heap to be expanded The size is the size of the allocation request passed by _umalloc You probably want to return enough memory at a time to satisfy several allocations otherwise every subsequent allocation has to call getmore_fn reducing your program s execution speed Make sure that you update the size parameter if you return more than the size requested Your function must also set the clean parameter to either BLOCK CLEAN to indicate the memory has been set to 0 or _ BLOCK CLEAN to indicate that the memory has not been initialized Th
228. ated to determine whether or not to process the body of the loop The expression must be convertible to a scalar type If the expression evaluates to 0 the body of the loop never runs If the expression does not evaluate to 0 the loop body is processed After the body has run control passes back to the expression Further processing depends on the value of the condition A break return or goto statement can cause a while statement to end even when the condition does not evaluate to 0 Related Reading l Ol Odde A Example Using the While Statement In the following program item index triples each time the value of the expression index is less than MAX_INDEX When index evaluates to MAX_INDEX the while statement ends define MAX_INDEX sizeof item sizeof item 0 include lt stdio h gt int main void static int item 12 55 62 85 102 int index 0 while index lt MAX_INDEX item index 3 printf item d d n index item index index return 0 Related Reading Ewhile Statement Labels A label is an identifier that allows your program to transfer control to other statements within the same function It is the only type of identifier that has function scope 158 C for AIX User s Guide Control is transferred to the statement following the label by means of the goto or switch statements The case and default label names are reserved for use within the body of t
229. atement In this example omitting the braces would cause the else clause to associate with the nested if statement if kegs gt 0 if furlongs gt kegs fpk furlongs kegs else fpk 0 The following example shows an if statement nested within an else clause This example tests multiple conditions The tests are made in order of their appearance If one test evaluates to a nonzero value a statement runs and the entire if statement ends if value gt 0 increase else if value 0 break_even else decrease Related Reading Null Statement The null statement performs no operation A null statement can hold the label of a labeled statement or complete the syntax of an iterative statement Related Reading Examples Using the Null Statement The following example initializes the elements of the array price Because the initializations occur within the for expressions a statement is only needed to finish the for syntax no operations are required for i 0 i lt 3 price it 0 A null statement can be used when a label is needed before the end of a block statement For example void func void if error_detected goto depart further processing depart null statement required Chapter 6 The C Language 153 Related Reading return A return statement ends the processing of the current function and returns control to the caller of the function Pi return To
230. ates a heap myheap and uses _debug_umalloc to allocate 100 bytes from it It then attempts to overwrite storage that was not allocated The call to debug free invokes uheap_check which detects the error generates messages and ends the program Note You must compile this example with the qheapdebug option to map _umalloc to _debug_umalloc and free to debug _ free include lt stdlib h gt include lt stdio h gt include lt umalloc h gt include lt string h gt int main void Heap _t myheap char ptrs Use default heap as user heap myheap _udefault NULL 432 for AIX Users Guide if NULL ptr char umalloc myheap 100 puts Cannot allocate memory from user heap n exit EXIT_FAILURE memset ptr x 105 Overwrites storage that was not allocated free ptr return 0 BRK k k KEK RRR KER KR ERR K k k Kk ER KERR RE RRR RK ER KEKE kk k kk ER ERE RK ERK ERR kkk KKK KKK KK KK The output should be similar to End of allocated object 0x00073890 was overwritten at 0x000738f4 The first eight bytes of the memory block in hex are 7878787878787878 This memory block was re allocated at line number 14 in _debug_umallo c Heap state was valid at line 14 of debug umallo c Memory error detected at line 19 of debug umallo c KK KKK KK KK KERR KERR ERK ERR EK RRR KERR RR RRR RRR KERR ARR KER KERR ERE EKER EKER ER EKER Related Reading Appendix F C for AIX Debug Functions 433 434 C fo
231. ation alone The maf functions provide an extension to the IEEE standard because they perform the multiply and add with one rather than two rounding errors The maf functions are both faster and more accurate than the equivalent separate operations Use the nomaf option to suppress the generation of these multiply add instructions Note PowerPC and Powers hardware can perform computations in either single or double precision Considerations regarding single precision do not apply to these platforms Detecting Floating Point Exceptions A number of floating point exceptions can be detected by the floating point hardware invalid operation division by zero overflow underflow and inexact By default all exceptions are ignored However if you use the flttrap option any or all of these exceptions can be detected For an example of how this works In addition when you add suitable support code to your program program execution can Soini after an exception occurs and you can then modify the results of operations causing exceptions Refer to Floating Point Processor Overview and Floating Point Exceptions in the AIX Version 4 Assembler Language Referencefor more information about RISC System 6000 floating point processing Related Reading AL On Oade 04 Compile Time Floating Point Arithmetic The compiler attempts to perform as much floating point arithmetic as possible at compile time Floating point operations with
232. ave been installed on your system any other valid national language code can be substituted for en_US To determine the current setting of the national language on your system use the both of the following echo commands echo LANG echo NLSPATH The LANG and NLSPATH environment variables are initialized when the operating system is installed and might differ from the ones you want to use You use different commands to set the environment variables depending on whether you are using the Bourne shell bshor sh Korn shell ksh or C shell csh To determine the current shell use the echo command echo SHELL The Bourne shell path is bin bsh or bin sh The Korn shell path is bin ksh The C shell path is bin csh For more information about the NLSPATH and LANG environment variables see AlX Version 4 System User s Guide Operating System and Devices The AIX international language facilities are described in the AIX General Programming Concepts for IBM RISC System 6000 Setting Environment Variables in bsh ksh or sh Shells To set the environment variables from the Bourne shell or Korn shell use the following commands LANG en_US NLSPATH usr 1lib nls msg L N usr 1ib nls msg N export LANG NLSPATH To set the variables so that all users have access to them add the commands to the file etc profile To set them for a specific user only add the commands to the file profile in the user s home directory The environme
233. b vertical tab and form feed ASCII 0 31 e The space character eo amp ets e 0123456789 23 lt gt e ABCDEFGHIJKLMNOPQRSTUVWXYZ a Oe ee abcdefghijkIimnopqrstuvwxyz e l e delete Related Reading 460 C for AIX User s Guide Type Conversions Type conversions are implementation dependent Tables on this page summarize type conversions of arithmetic types Arithmetic types include signed and unsigned integral types char int shortand long in addition to float double and long double types e Type Conversions Signed Integer Types table page ed e Type Conversions Unsigned Integer Types table page Led e Type Conversions Floating Point Types table page ed e Converting Pascal String Literals page Lea e Integral Promotion page bed Type Conversions Signed Integer Types signed short Preserve None sign extend sign extend sign extend low order bytes Preserve Preserve None Preserve bit sign extend low order bytes low order bytes pattern Preserve Preserve Preserve None sign extend low order bytes low order bytes low order bytes signed long long Preserve Preserve Preserve Preserve None low order bytes low order bytes low order bytes low order bytes unsigned char Preserve bit Zero extend Zero extend Zero extend Zero extend pattern high order bit becomes sign bit unsigned short Preserve Preserve bit Zero extend Zero extend Zero extend low order bytes pattern high o
234. b crt0 o lib mcrt0 o lib gcrt0 o L usr lib threads L usr vacpp lib 1C lpthreads compat pthreads lc_r m usr lib libc a L usr vacpp 1lib profiled L lib profiled L usr 1ib profiled L usr vac 1ib 1hC 1hmd qansialias qthreaded D THREAD SAFE D_VACPP MULTI D AIX PTHREADS D7 x x1C C compiler with 128 bit long double aliased as x1C128 r7 AIX POSIX Draft 7Threads x1C128 r7 use crt mcrt lt DEFLT lib crt0 o 1ib mcrt0 o 480 cC for AIX User s Guide gcrt lib gcrt0 o libraries2 L usr lib threads L usr vacpp 1ib 1C128 1C lpthreads compat 1m pthreads 1c128 1c proflibs L usr vacpp 1lib profiled L lib profiled L usr 1lib profiled hdlibs L usr vac 1lib 1hC 1hmd options qansialias qldb1128 qthreaded D THREAD SAFE D VACPP MULTI D AIX PTHREADS D7 common definitions DEFLT cppcomp usr vacpp exe x1Centry ccomp usr vac exe xlcentry code usr vac exe x1Ccode cpp usr vac exe x1Ccpp munch usr vacpp exe munch ipa usr vac exe ipa dis usr vac exe dis cppfilt usr vacpp bin ct filt bolt usr vac exe bolt as bin as Id bin d xIC usr vacpp bin x1C cppinc usr vacpp include options D AIX D AIX32 D AIX41 D AIX43 D_IBMR2 D POWER bpT 0x10000000 bpD 0x20000000 ldopt b o e u R H Y Z L T A k j hdlibs L usr vac lib 1hmd xlCcopt qansialias crt_64 lib crt0 64 0 mcrt_64 lib mcrt0_64 0 gcrt_ 64 lib gcrt0 64 0
235. ber qrrm must also be specified if the Floating Point Status and Control register is changed at run time 318 C for AIX User s Guide The default qnorrm generates code that is compatible with run time rounding modes nearest and zero For a list of rounding mode options see the y compiler option This option is obsolete Use qfloat rrm in your new applications Related Reading Option Type Default Value pragma options e Syntax S Purpose Generates an assembler language file s for each source file The resulting s files can be assembled to produce object o files or an executable file a out Notes You can invoke the assembler with the xlc command For example xlc myprogram s will invoke the assembler and if successful the loader to create an executable file a out If you specify S with E or P E or P takes precedence Note the following order of precedence with respect to the S option 1 E overrides P 2 P overrides S 3 S overrides c This order of precedence holds regardless of the order in which they were specified on the command line You can use the o option to specify the name of the file produced only if no more than one source file is supplied For example the following is not valid xlc myprograml c myprogram2 c o S Restrictions The generated assembler files do not include all the data that is included in a o file by the g or qipa options Example To compile mypro
236. bs options xlc128 r4 xlc128 r4 use crt mcrt gcrt libraries proflibs hdlibs options standard c compiler cc_r4 use cre mcrt gcrt libraries proflibs hdlibs options cc128_r4 cc128 r4 use crt mcrt gcrt libraries proflibs DEFLT lib crt0 o lib mcrt0 o lib gcrt0 o L usr lib threads L usr vacpp lib 1C128 1C lpthreads 1c128 1m 1c L usr vacpp lib profiled L lib profiled L usr lib profiled L usr vac lib 1hC 1hmd qansialias qldbl128 qthreaded D_THREAD_SAFE D__VACPP_MULTI _ aliased as xlc_r4 DCE DEFLT lib crt0 o lib mcrt0 o lib gcrt0 o L usr lib threads ldcelibc_r ldcepthreads lpthreads_ compat lIpthreads 1c L lib profiled L usr lib profiled L usr vac lib 1hmd qansialias qthreaded D THREAD SAFE D_VACPP MULTI D AIX PTHREADS D7 D AIX32_THREADS 1 D Al DEFLT lib crt0 o lib mcrt0 o lib gcrt0 o L usr 1lib threads ldcelibc_r ldcepthreads lpthreads_ compat lIpthreads 1c128 1c L lib profiled L usr lib profiled L usr vac 1lib 1hmd qansialias qthreaded D THREAD SAFE D_VACPP_MULTI__ D AIX PTHREADS D7 D AIX32_THREADS 1 D A aliased as cc_r4 DCE DEFLT lib crt0 o lib mcrt0 o0 lib gcrt0 o L usr lib threads ldcelibc_r ldcepthreads lpthreads compat Ipthreads 1c L lib profiled L usr lib profiled L usr vac 1lib 1hmd qlanglvl extended qnoro qnoroconst qthreaded D_ THREAD SAFE D VACPP_ MULTI _ D AIX _PTHREADS D DEFLT l1ib c
237. bstitutes inline code for calls to function alloca as if pragma alloca directives are in the source code Notes lf pragma alloca is unspecified or if you do not use ma alloca is treated as a user defined identifier rather than as a built in function Example To compile myprogram c so that calls to the function alloca are treated as inline enter xlc myprogram c ma Related Reading macpstr Option Type Default Value pragma options Syntax qmacpstr qnomacpstr MACPSTR NOMACPSTR Purpose Converts Pascal string literals into null terminated strings where the first byte contains the length of the string Notes A Pascal string literal always contains the characters p The characters p in the middle of a string do not form a Pascal string literal the characters must be immediately preceded by the double quote character The final length of the Pascal string literal can be no longer than 255 bytes the maximum length that can fit in a byte For example the qmacpstr converts pABC 03 A A B IC 0 The compiler ignores the qmacpstr option when the qmbcs or qdbcs option is active because Pascal string literal processing is only valid for one byte characters Appendix A Compiler Options 295 The pragma options keyword MACPSTR is only valid at the top of a source file before any C statements If you attempt to use it in the middle of a source file it is ignored and the compiler
238. can save file space by making the following changes to your etc vac cfg compiler configuration file 1 Remove the qtable full option from the options lines of the C compilation stanzas 2 Remove the qtable full option from the xlCopt line of the DFLT stanza With these changes the defaults for the tbtable option are e When compiling with optization options set qtbtable small e When compiling with no otimization options set qtable full 2 3 4 for a brief description of traceback tables The AIX Version 4 traceback mechanism is described in the Subroutine Linkage Convention section of the 330 C for AIX User s Guide AIX Version 4 Assembler Language Reference Related Reading threaded Option Type Default Value pragma options OO awo Seow Syntax qthreaded qnothreaded Purpose Indicates to the compiler that the program will run in a multi threaded environment Always use this option when compiling or linking multi threaded applications Notes This option applies to both compile and linkage editor operations To maintain thread safety a file compiled with the qthreaded option whether explicitly by option selection or implicitly by choice of _r compiler invocation mode must also be linked with the qthreaded option This option does not make code thread safe but it will ensure that code already thread safe will remain so after compile and linking Default The default is qthreaded when compiling
239. can use the xlc command to preprocess the source file without compiling by specifying either the E or the P option If you specify the P option a preprocessed source file file_name i is created and processing ends The E option preprocesses the source file writes to standard output and halts processing without generating an output file Preprocessed source files have a i suffix for example file_name i The xic command sends the preprocessed source file file_name i to the compiler where it is preprocessed again in the same way as a c file Preprocessed files are useful for checking macros and preprocessor directives Object files must have an o suffix for example year o Object files library files and nonstripped executable files serve as input to the linkage editor After compilation the linkage editor links all of the specified object files to create an executable file Assembler files must have an s suffix for example check s Assembler files are assembled to create an object file Extended Common Object File Format XCOFF files that have not been stripped with the AIX strip command can be used as input to the compiler See the strip command in the AIX Version 4 Commands Reference and the description of a out file format in the AlX Version 4 Files Reference for more information Chapter 3 Using the C for AIX Compiler 7 Types of Output Files You can specify the following types of output files when invoking the
240. ce of preprocessor actions pro Missing function prototypes rea Code that cannot be reached ret Consistency of return statements trd Possible truncation or loss of data or precision tru Variable names truncated by the compiler uni Unitialized variables use Unused auto and static variables vft Generation of virtual function tables Related Reading Option Type Default Value pragma options 2760 C for AIX User s Guide Syntax qinitauto hex_value qnoinitauto INITAUTO hex value NOINITAUTO Purpose Initializes automatic storage to the two digit hexadecimal byte value hex_value The option generates extra code to initialize the automatic stack allocated storage of functions It reduces the runtime performance of the program and should only be used for debugging Notes There is no default setting for the initial value of qinitauto you must set an explicit value for example qinitauto FA Example To compile myprogram c so that automatic stack storage is initialized to hex value FF decimal 255 enter xlc myprogram c qinitauto FF Related Reading inlglue Option Type Default Value pragma options Syntax qinlglue qnoinlglue INLGLUE NOINLGLUE Purpose Generates fast external linkage by inlining the pointer glue code necessary to make a call to an external function or a call through a function pointer Notes Glue code generated by the linker is used for passing control between two external f
241. ce type Related Reading Built in Functions Used for Parallel Processing Your program can use these built in functions to modify or obtain information about the parallel environment Function definitions for the omp_ functions can be found in the omp h header file int parthds void This function returns the value of the parthds run time 7 option If the parthds option is not explicitly set by the user the function returns the default value set by the run time library If the qsmp compiler option was not specified during program compilation this function returns 1 regardless of run time options selected int _usrthds void Sci function returns the value of the usrthds run time option If the usrthds option is not explicitly set by the user or the qsmp compiler option was not specified during program compilation this function returns 0 regardless of run time options selected int omp_set_num threads int num threads This function must be called from a serial portion of your program e If dynamic adjustment of the number of threads is enabled this function sets num_threads as the maximum number of threads to use for subsequent parallel regions If dynamic adjustment of the number of threads is disabled this function causes num_threads to be used as the number of threads for all subsequent parallel regions The value of num_threads must be a positive integer This function takes overrides the setting of the OMP_N
242. cified for sev_level the current value of the qhalt option is used The default value for qhalt is s severe error If the qmaxerr option is specified more than once the qmaxerr option specified last determines the action of the option If both the qmaxerr and ghalt options are specified the qmaxerr or qhaltoption specified last determines the severity level used by the qmaxerr option Messages suppressed by the qsuppress option are not counted An unrecoverable error occurs when the number of errors reached the limit specified The error message issued is similar to 1506 672 U The number of errors has reached the limit of If qnomaxerr is specified the entire source file is compiled regardless of how many errors are encountered Diagnostic messages may be controlled by the qflag and qsuppress options Examples 1 To stop compilation of myprogram c when 10 warnings are encounted enter the command xlc myprogram c qmaxerr 10 w 1 To stop compilation of myprogram c when 5 severe errors are encounted assuming that the current qhalt option value is S severe enter the command xlc myprogram c qmaxerr 5 1 To stop compilation of myprogram c when 3 informationals are encountered enter the command Appendix A Compiler Options 299 xlc myprogram c qmaxerr 3 1 Or xlc myprogram c qmaxerr 5 w qmaxerr 3 ghalt i Related Reading maxmem Option Type Default Value pragma options Syntax qmax
243. cleanpdf you must recompile all the files with qpdf1 Example 1 Here are the steps for a simple example 1 First set the PDFDIR environment variable export PDFDIR home user 2 Compile all files with qpdf1 and O3 and link with Ipdf xlc qpdfl lpdf 03 filel c file2 c file3 c L usr vac lib 3 Run with one set of input data a out lt sample data 4 Recompile all files with qpdf2 and O3 xlc qpdf2 03 filel c file2 c file3 c 310 C for AIX User s Guide The program should now run faster than without PDF if the sample used data was typical of actual program data Note When using qpdf1 specify the search location for its libraries with the L compiler option as shown in step 2 above Example 2 Here are the steps for a more elaborate example 1 Set the PDFDIR environment variable export PDFDIR home user 2 Compile most of the files with qpdf1 xlc qpdf1 03 c filel c file2 c file3 c L usr vac lib 3 This file is not so important to optimize xlc c file4 c 4 Non PDF object files like file4 0 can be linked in xlc qpdfl lpdf filel o file2 o file3 o0 file4 0 L usr vac lib 5 Run several times with different input data a out lt polar _orbit data a out lt elliptical orbit data a out lt geosynchronous orbit data 6 You do not need to recompile the source of non PDF object files xlc qpdf2 03 filel c file2 c file3 c 7 Link all the object files into the final application xlc
244. code are executed by multiple threads possibly running on multiple processors The number of threads created is determined by run time options and calls to library functions Work is distributed among available threads according to the directives specified in the source Note The qsmp option must only be used together with thread safe compiler invocation modes IBM Directives IBM directives exploit shared memory parallelism through the parallelization of countable loops A loop is considered to be countable if it has any of the forms described in Countable Loops The compiler can automatically locate and where possible parallelize all countable loops in your program code In general a countable loop is automatically parallelized only if all of the follow conditions are met e the order in which loop iterations start or end does not affect the results of the program e the loop does not contain I O operations e floating point reductions inside the loop are not affected by round off error unless the qnostrict option is in effect e the qnostrict_induction compiler option is in effect e the qsmp compiler option is in effect without its omp suboption The compiler must be invoked using a thread safe compiler mode You can also use the IBM directives to explicitly instruct the compiler to parallelize selected countable loops The C for AIX compiler provides pragma directives that you can use to improve on automatic parallelization p
245. complete definition of find max Note The use of the sizeof operator in line 13 is a standard method of determining the number of elements in an array 1 x 2 Example of void type 3 4 include lt stdio h gt 5 6 declaration of function find max 7 extern void find max int x int j 8 9 int main void 10 11 static int numbers 99 54 102 89 12 13 find_max numbers sizeof numbers sizeof numbers 0 14 15 return 0 16 17 18 void find_max int x int j 19 begin definition of function find max 20 int i temp x 0 21 22 for i 1 i lt j i 23 24 if x i gt temp Chapter 6 The C Language 85 25 temp x i 26 27 printf max number d n temp 28 end definition of function find_max Related Reading Derived Data Types Arrays An array is an ordered group of data objects Each object is called an element All elements within an array have the same data type Use any type specifier in an array definition or declaration Array elements can be of any data type except function You can however declare an array of pointers to functions Declaring an Array a E constant expresion constant_expression identifier The name of the array If preceded by an asterisk the array is an array of pointers constant expression Positive integer expression describing the number of elements in a given dimension of
246. cond and third operands determine the type of the result as shown below Type of One Operand Type of Other Operand Type of Result Arithmetic Arithmetic Arithmetic type after usual arithmetic conversions Structure or union type Compatible structure or union type Structure or union type with all the qualifiers on both operands Pointer to compatible type Pointer to compatible type Pointer to type NULL pointer the constant 0 Pointer to object or incomplete type Pointer to void Related Reading a af Pointer Arithmetic page b2 Examples Using the Conditional Operator The following expression determines which variable has the greater value y or z and assigns the greater value to the variable x x y gt z y Z The following is an equivalent statement 132 C for AIX Users Guide X y else X Z The following expression calls the function printf which receives the value of the variable c if c evaluates to a digit Otherwise printf receives the character constant x printf c c n isdigit c c x If the last operand of a conditional expression contains an assignment operator use parentheses to ensure the expression evaluates properly For example the operator has higher precedence than the operator in the following expression int i j k ees 7 Po are kes This expression generates and error because it is interpreted as if it were parenthesized this way int i j k
247. constant operands are folded replacing the operation with the result calculated at compile time When the O option is used more folding might occur than when optimization is not enabled All compile time folding of floating point computations can be suppressed using the float nofold option Alternatively the IEEE rounding mode used in compile time arithmetic can be controlled using the y options Compile time floating point arithmetic can have two effects on program results e In specific cases the result of a computation at compile time might differ slightly from the result that would have been calculated at run time The reason is that more rounding operations occur at compile time For example where a maf operation might be used at run time separate multiply and add operations might be used at compile time producing a slightly different result e Computations that produce exceptions can be folded to the IEEE result that would have been produced by default in a runtime operation This would prevent an exception from occurring at run time When using the flttrap option you should consider using the float nofold option 26 C for AIX User s Guide In general code that affects the rounding mode at run time should be compiled with the y option that matches the rounding mode intended at run time For example when the following program main float x y int i x 1 0 3 0 i int amp x printf 1 3 8x n i
248. cpp lib mcrt0 o usr vacpp lib gcrt0 o L usr vacpp lib 1C 1m 1c L usr vacpp lib profiled L lib profiled L usr lib profiled L usr vac lib 1hC 1hmd qansialias C compiler with 128 bit long double x1C128 use crt mcrt gcrt libraries2 proflibs hdlibs options DEFLT usr vacpp lib crt0 o usr vacpp lib mcrt0 o usr vacpp lib gcrt0 o L usr vacpp 1ib 1C128 1C Im 1c128 1c L usr vacpp 1lib profiled L lib profiled L usr 1lib profiled L usr vac lib 1hC 1hmd qansialias qldb1128 standard c compi ler aliased as xlc_r AIX Threads xic r use crt mcrt gcrt libraries proflibs hdlibs options DEFLT lib crt0_r o lib mcrt _r o lib gcrt r o L usr lib threads lpthreads lc_r usr lib libc a L lib profiled L usr lib profiled L usr vac lib lhmd_r qansialias qthreaded D_ THREAD SAFE D VACPP MULTI _ standard c compiler aliased as cc_r AIX Threads cc r x1c128 r use Cru mert gcrt libraries proflibs hdlibs options use crt mcrt gcrt libraries proflibs DEFLT lib crt0_r o lib mcrt _r o lib gcrt r o L usr lib threads lpthreads lc_r usr lib libc a L lib profiled L usr lib profiled L usr vac lib lhmd_r qlanglvl extended qnoro qnoroconst qthreaded D_ THREAD SAFE D_VACPP MULTI _ DEFLT lib crt0_r o lib mcrt _r o lib gcrt0_r o L usr lib threads lpthreads 1c128_r 1c128 1c_r usr lib libc a L lib p
249. ction that returns a pointer should be explicitly declared when compiling in 64 bit mode Otherwise the compiler will assume the function returns an int and truncate the resulting pointer even if you were to assign it into a valid pointer Code such as a char calloc 25 which used to work in 32 bit mode will in 64 bit mode will now silently get a truncated pointer Even the type casting will not avoid this because the calloc has already been truncated after the return The fix in this case is to include the appropriate header file which is stdlib h and not malloc h Structure Sizes and Alignments Structures may face potential porting problems The 64 bit specification changes the size member and structure alignment of all structures that are recompiled in 64 bit mode Structures with long types and pointers will generally change size and alignment in 64 bit mode Some structures may not change in size because they happen to fall on an exact 8 byte boundary even in 32 bit mode Sharing data structures between 32 and 64 bit processes is no longer possible unless the structure is devoid of pointer and long types Unions that attempt to share long and int types or overlay pointers onto int types will now be aligned differently or be corrupted In general all but the simplest structures must be checked for alignment and size dependencies The alignment for qalign full power or natural changes for 64 bit mode Structure members are al
250. ctives are BRK RE KKK KEK k k k RRR ERR RE RRR RK K k KER KERR KK ER ERE k K k KK EKER ER ERK k Kk KK KK KKK KE In the following example only header file hl h is precompiled and the precompiled output is written to the file csetc pch provided the qgenpcomp compiler option is specified If both qusepcomp dave pch and qgenpcomp john pch are specified then the compiler looks for the precompiled header in john pch since this is the name specified last and regenerates it if it is not found or unusable KKK KEK KK KKK KEK KEK KERR ERK EK RRR KEK KEKE RRR EKER KERR KR ERE ERK ERE EKER KERR kk kk kk kk include h1 h pragma hdrstop include h2 h main BRK RE KK EK KEK KERR KK EKER RRR RRR RK ER KEK REE KK k k ERE k K k KK EKER ER ERK KKK REE k Kk KE Appendix D Preprocessor Directives and Related Information 369 In the following example no precompiled headers are generated or used for the compilation even if qgenpcomp or qusepcomp compiler options are specified KK KKK KK KE KERR Kk KEk Kk Kk KEk RR Kk kkk kk kkk KKK ER ARR KERR ERK EKER kK Kk kkk kk Kk RE pragma hdrstop include h1 h include h2 h main Related Reading pragma info Preprocessor Directive The pragma info directive controls the diagnostic messages generated by the info compiler option P 4 pragma info i cll 4 restcre group You can use this directive in place of the info option to turn
251. cts 32 bit compiler mode e q64 selects 64 bit compiler mode e qarch selects the general family processor architecture for which code instructions should be generated Certain qarch settings will produce code that will run only on RS 6000 systems that support all of the instructions generated by the compiler in response to the chosen qarch settings e qtune selects the specific processor for which compiler output is optimized Some qtune settings can also be specified as qarch options in which case they do not also need to be specified as a qtune option The qtune option influences only the performance of the code when running on a particular system but does not determine where the code will run There are three families of RS 6000 machines e POWER e POWER2 e PowerPC Each of these families have a different instruction set but share a common subset of instructions The POWER2 instruction set is a superset of the POWER instructions set The PowerPC instruction set includes additional instructions not available on POWER systems but does not support all of the POWER instruction set It also includes some but not all of the POWER2 instructions not available in the POWER instruction set Further some features found in the POWER2 instruction set may or may not be implemented on particular PowerPC processors These optional feature groups are e support for the graphics instruction group e support for the sart instruction group e suppor
252. cture SAA Common Programming Interface C language definition described by the document Systems Application Architecture Common Programming Interface C Reference Level 2 SAA Level 2 is an IBM definition of the C language that allows programmers to develop applications that can be easily transported across different SAA environments It specifies several features of the C language that the ANSI C standard designates as implementation defined e Compiler options to provide support for different levels and features of the C language e Compiler options to enable various levels of optimization for generated object code e Unicode character support lets you use characters not in the basic character set to describe identifiers character constants and string literals e Memory debug routines e xIdb and IBM Distributed Debugger idebug graphical debugger tools e HTML based product help and reference information Copyright IBM Corp 1995 1999 1 2 C for AIX Users Guide Chapter 2 Setting Up the C for AIX Compilation Environment Before you compile your C programs you must set up the environment variables and the configuration file for your application Setting Environment Variables to Select 64 or 32 bit Compilation Modes The OBJECT MODE environment variable if it exists can set the default compilation mode Permissible values for the OBJECT MODE environment variable are 32 Sets the compiler to generate and or use 32 bit objects
253. cupying one or more words The methods of passing parameters are as follows e In C all function arguments are passed by value and the called function receives a copy of the value passed to it e In Fortran by default arguments are passed by reference and the called function receives the address of the value passed to it You can use the VAL Fortran built in function to pass by value Refer to the AIX XL Fortran Compiler 6000 User s Guidefor more information about using VAL and interlanguage calls e In Pascal the function declaration determines whether a parameter is expected to be passed by value or by reference Related Reading Interlanguage Calls Call by Reference Parameters For call by reference as in Fortran the address of the parameter is passed in a register When passing parameters by reference if you write C function that e you want to call from a Fortran program declare all parameters as pointers e calls a program written in Fortran all arguments must be pointers or scalars with the address operator e you want to call from a Pascal program declare as pointers all parameters that the Pascal program treats as reference parameters e calls a program written in Pascal all arguments corresponding to reference parameters must be pointers 210 C for AIX User s Guide Related Reading Interlanguage Calls Call by Value Parameters In prototype functions with a variable number of arguments speci
254. d For example enum frog toad 257 amph 1506 387 W The enum cannot be packed to the requested size Use a larger value for qenum The enum size is 1 and the value of toad is 1 For every pragma options enume directive that you put in your program it is good practice to have a corresponding pragma options reset as well This is the only way to prevent one file from potentially changing the enume setting of another file that includes it It is good practice to specify pragma options enum reset at the end of any file that contains pragma options enume directives The table below shows the priority for selecting a predefined type It also shows the the predefined type the maximum range of enum constants for the corresponding predefined type and the amount of storage that is required for that predefined type that is the value that the sizeof operator would yield when applied to the minimum sized enum Priority of Choosing Predefined enum Types inclusive bytes short signed short int 32767 1 to 32767 int signed int int 2 147 483 647 1 to 2 147 483 647 8 lowest signed long signed long a to O a 8 see Note Note Long enum types are valid only in 64 bit compiler mode e When you specify pragma options enum small the option stays in effect until it is explicitly turned off with a pragma options enumz int or pragma options enume reset directive e f you compile the file using the qenum int o
255. d without an explicit cast Assignment of pointers to Supported Not Supported Supported different types Enumeration declarations Supported Not Supported Supported with trailing extra comma Functions without definition Supported Not Supported Supported accepted and defined extern Definition of static function Not Required Not Required sizeof operator on bit fields Supported Not Supported Supported Chapter 6 The C Language 171 Array initialization without Supported Not Supported Not Supported braces Last member of a structure Supported Not Supported Not Supported definition not terminated by a semicolon character in identifiers Permitted Prohibited Permitted Macro concatenation using Supported Not Supported Supported 172 C for AIX User s Guide Chapter 7 Writing C Programs A C program typically passes through four steps of development External source code j c files Preprocessed i i files Object files o files Archive libraries SS i a Files C for AY C source code c files Preprocessed source i files Assembler files i s files Targets from M option iu files Compiler Listings ist files Object files o files Listings and Reports Executable file Program output The solid lines show inputs into each step of the development cycle Compile and Linkage Editor operations are performed by the C for AIX product
256. d Reading Example of Reading and Writing to Mapped to I O Space The following example assumes a special machine with three hardware locations There is an input data buffer at OxFFFFFF20 There is an output data buffer at OxFFFFFF24 There is a control data buffer at OxFFFFFF28 The third least significant bit set in the control buffer indicates there is data in the input buffer This bit is unset when the data is read out of the input buffer by the program The second least significant bit set in the control buffer indicates the output device is ready to accept output data This bit is unset when the data is placed in the output buffer and is read out typedef unsigned long datatype controltype counttype define CONTROLLER const volatile controltype const OxFFFFFF28 define INPUT BUF const volatile datatype const OxFFFFFF20 define OUTPUT BUF volatile datatype const OxFFFFFF24 define INPUT READY BIT 0x4 define OUTPUT READY BIT 0x2 define INPUT READY CONTROLLER amp INPUT READY BIT define OUTPUT READY CONTROLLER amp OUTPUT READY BIT The function copy data copies data from the input buffer to the output buffer until an input value of O is seen Appendix Implementation Dependencies Overview 465 The number of characters copied is returned Make count of the input global so that other CPUs can access it counttype volatile count 0 counttype copy data datatype temp To
257. d as double or double a in the prototype since ANSI states that all narrow type arguments such as chars shorts and floats are widened before they are passed to K amp R functions Related Reading halt Option Type Default Value pragma options Syntax qghalt severity HALT severity Purpose Instructs the compiler to stop after the compilation phase when it encounters errors of specified severity or greater Notes severity is one of severity Description i Information wW Warning e Error S Severe error u Unrecoverable error When the compiler stops as a result of the qhalt option the compiler return code is nonzero When ghalt is specified more than once the lowest severity level is used The ghalt option can be overridden by the qmaxerr option Diagnostic messages may be controlled by the qflag option Appendix A Compiler Options 269 Example To compile myprogram c so that compilation stops if a warning or higher level message occurs enter xlc myprogram c ghalt w Related Reading heapdebug Option Type Default Value pragma options Syntax qheapdebug Purpose Enables debug versions of memory management functions Notes The qheapdebug options specifies that the debug versions of memory management functions _debug_calloc debug malloc new etc be used in place of regular memory management functions This option defines the _ DEBUG_ALLOC __ macro When you specify qheapdebug
258. d is at a word boundary the next bit field starts at this boundary e A struct containing nothing but zero width bit fields is allowed and will have a length of O bytes In the C language you can specify bit fields as char or short instead of int but the compiler maps them as if they were unsigned int In extended mode you can use the sizeof operator on a bit field The sizeof operator on a bit field always returns 4 Copyright IBM Corp 1995 1999 437 Related Reading Alignment Rules for Nested Aggregates Aggregates with different alignments can be nested Each aggregate is laid out using the alignment rules applicable to it The start position of the nested aggregate is determined by the alignment rules of the aggregate in which it is nested Example The following example uses these symbols to show padding and boundaries p padding halfword boundary byte boundary For pragma options align mac68k struct A char a pragma options align power struct B int b char C Bl lt Bl laid out using RISC System 6000 alignment rules pragma options align reset lt has no effect on A or B but on subsequent structs char d 3 sizeof A 12 The layout of A is a p b b b b c p p p d p Related Reading Packed Alignment Rules All structures are byte aligned regardless of their members All members are also byte aligned Bit fields are byte aligned but bit field members are
259. d of width 16 or less have a size of 2 bytes If the width of the bit field is greater than 16 the size of the union is 4 bytes Example The following example uses these symbols to show padding and boundaries padding halfword boundary byte boundary p For pragma options align mac68k struct A char a int 0 int b 4 int 173 sizeof A 8 The layout of A is a p b plc c c p Type Compatibility between RISC System 6000 and Macintosh Systems Different aggregate types with identical members are not compatible Therefore such aggregates cannot be assigned to each other Use the qextchk option to assure type safe linkage for function declarations that may use different alignment rules Appendix H RISC System 6000 Alignment Rules 441 Related Reading __align Specifier Syntax declarator _ align integer constant identifier struct_or_union specifier align integer constant identifier struct_declaration list where integer_constaptcifies a byte alignment boundary integer_constant must be an integer greater than 0 and equal to a power of 2 Purpose Use the __ align specifier to explicitly specify alignment and padding when declaring or defining data items Notes The __ align specifier can only be used with declarations of first level variables and aggregate definitions It ignores parameters and automatics The __align specifier cannot be used on individual elements within an a
260. d to a signed char the lowest byte of the integer is used to represent the char 3 2 1 2 Appendix Implementation Dependencies Overview 449 When an integer is converted to a shorter signed integer the lowest 2 bytes of the integer are used to represent the short int 3 2 1 2 When an unsigned integer is converted to a signed integer of equal length the bit pattern is preserved and the high order bit becomes the sign bit 3 2 1 2 nw Bitwise operations Inclusive OR AND amp Exclusive OR on a signed integer use the bit pattern of the signed quantity 3 3 lf either operand of integer division is negative the result of the operator is the largest integer less than or equal to the algebraic quotient 3 3 5 When a bitwise right shift gt gt of a negative signed integral type is used vacated bits are filled with ones 3 3 7 When a bitwise right shift of a non negative signed integral type or an unsigned integral type is used vacated bits are filled with zeros When using long long in your programs the following rules apply e The size of pointers remains 32 bit e An integer constant has type long long int only if it is suffixed by the letters Il e An integer constant with suffix Il has type long long int or unsigned long long int An integer with suffix ull or Ilu has type unsigned long long int e Integral promotions are unchanged Integral promotions are not performed on long long ints e Conver
261. d to match the layout of the left This remapping of structures might degrade performance For efficiency when you perform assignment operations with structures or unions you should ensure that both operands are either packed or nonpacked Note If you assign pointers to structures or unions the objects they point to must both be either packed or nonpacked You can assign values to operands with the type qualifier volatile You cannot assign a pointer of an object with the type qualifier const to a pointer of an object without the const type qualifier For example const int pl int p2 p2 pl this is NOT allowed pl p2 this IS allowed Note The assignment operator should not be confused with the equality operator For example if x 3 evaluates to 1 if x is equal to three Equality tests like this should be coded with spaces between the operator and the operands to prevent unintentional assignments if x 3 is taken to be true because x 3 evaluates to a non zero value 3 The expression also assigns the value 3 to x 134 C for AIX Users Guide Compound Assignment The compound assignment operators consist of a binary operator and the simple assignment operator They perform the operation of the binary operator on both operands and give the result of that operation to the left operand The following table shows the operand types of compound assignment expressions Operator Left Operand
262. d to multiple simultaneous writing threads Syntax pragma omp atomic statement where statement is an expression statement of scalar type that takes one of the forms that follow x bin_op expr where bin_op is one of amp lt lt gt expr is an expression of scalar type that does not reference x Notes Load and store operations are atomic only for object x Evaluation of expr is not atomic All atomic references to a given object in your program must have a compatible type Appendix E Parallel Processing Facilities 397 Objects that can be updated in parallel and may be subject to race conditions should be protected with the omp atomic directive Examples extern float x p x y Protect against race conditions among multiple updates pragma omp atomic x Lindex i y Protect against races with updates through x x pragma omp atomic pli 1 0f Related Reading pragma omp flush Preprocessor Directive The omp flush directive identifies a point at which the compiler ensures that all threads in a parallel region have the same view of specified objects in memory Syntax pragma omp flush list where listis a comma separated list of variables that will be synchronized Notes If ist includes a pointer the pointer is flushed not the object being referred to by the pointer If ist is not specified all shared objects are synchronized except those inaccessible with au
263. dard c compiler aliased as xlc_r4 DCE xlc_r4 use DEFT crt lib crt0_r o mert lib mcrt0_r o gcrt lib gcrt0_r o libraries L usr lib threads ldcelibc_r ldcepthreads lpthreads lc_r lc proflibs L lib profiled L usr 1ib profiled hdlibs L usr vac lib lhmd_r options qansialias qthreaded D THREAD SAFE D VACPP MULTI D AIX32_THREADS 1 D AES SOURCE D AIX41 I x Standard c compiler aliased as cc _r4 DCE cc_r4 use DEFLT crt lib crt0_r o mert lib mcrt r o gcrt lib gcrt0 r o libraries L usr lib threads ldcelibc_r ldcepthreads lpthreads lc_r lc proflibs L lib profiled L usr 1lib profiled hdlibs L usr vac lib lhmd_r options qlanglvl extended qnoro qnoroconst qthreaded D THREAD SAFE D_ VACPP MULTI D AIX32_THREADS 1 xlc128 r4 use DEPLT Cre lib crt0_r o mert lib mcrt0 r o gcrt lib gcrt0 r o libraries L usr lib threads ldcelibc_r ldcepthreads lpthreads 1c128_r 1c128 lc_r lc proflibs L lib profiled L usr lib profiled hdlibs L usr vac lib lhmd_r options qansialias qldbl128 qthreaded D THREAD SAFE D_VACPP MULTI _ C compiler extended mode ccl28 r4 use DEFLT Crt lib crt0_r o mert lib mcrt0 r o gcrt lib gcrt0 r o libraries L usr lib threads ldcelibc_r ldcepthreads lpthreads 1c128_r 1c128 lc_r lc proflibs L lib profiled L usr lib profiled hdlibs L usr vac lib lhmd_r options qlanglvl extended qnoro qnoroconst qldbl
264. data in that memory without initializing it first In addition debug _realloc makes an implicit call to heap check and stores the file name file and the line number line where the storage is reallocated This information can be used later by the _heap_check dump_allocated or _dump_allocated_delta functions If ptr is NULL _debug_realloc behaves like _debug_ malloc or malloc and allocates the block of memory To use _debug realloc you must compile with the debug memory qheapdebug compiler option This option maps all realloc calls to _debug_realloc Note The qheapdebug option maps all calls to memory management functions including heap specific versions to their debug counterparts To prevent a call from being mapped parenthesize the function name Because _debug_realloc always checks what heap the memory was allocated from you can use _debug_realloc to reallocate memory blocks allocated by the regular or debug versions of the memory management functions However if the memory was not allocated by the memory management functions or was previously freed debug_realloc generates an error message and the program ends Return Value _debug_realloc returns a pointer to the reallocated memory block The ptr argument to _debug_realloc is not the same as the return value debug _realloc always changes the memory location to help you locate references to the memory that were not freed before the memory was reallocated If size is 0 deb
265. de directive After macro replacement the resulting token sequence must consist of a file name enclosed in either double quotation marks or the characters lt and gt For example define MONTH lt july h gt include MONTH If the file name is enclosed in double quotation marks the preprocessor searches the place for example directories or libraries that contain the source files and then a standard or specified sequence of places until it finds the specified file For example include payroll h If the file name is enclosed in the characters lt and gt the preprocessor searches only the standard or specified places for the specified file For example include lt stdio h gt The I compiler option specifies a search path if the file name in the include directive is not an absolute path 356 C for AIX User s Guide Related Reading Examples of the include Preprocessor Directive Example 1 Declarations that are used by several files can be placed in one file and included with include in each file that uses them For example the following file defs h contains several definitions and an inclusion of an additional file of declarations defs h define TRUE 1 define FALSE 0 define BUFFERSIZE 512 define MAX ROW 66 define MAX COLUMN 80 int hour int min int sec include mydefs h You can embed the definitions that appear in defs h with the following directive include defs h
266. dentifier kitchen to be of type struct on_off struct on_off unsigned light 1 unsigned toaster 1 int count 4 bytes unsigned ac 4 unsigned 4 unsigned clock 1 unsigned 0 unsigned flag 1 kitchen 98 C for AIX User s Guide The structure kitchen contains eight members totalling 16 bytes The following table describes the storage that each member occupies Member Name Storage Occupied light 1 bit toaster 1 bit padding 30 bits to next int boundary count the size of an int ac 4 bits unnamed field 4 bits clock 1 bit padding 23 bits to next int boundary unnamed field flag 1 bit padding 31 bits to next int boundary All references to structure fields must be fully qualified For instance you cannot reference the second field by toaster You must reference this field by kitchen toaster The following expression sets the light field to 1 kitchen light 1 When you assign to a bit field a value that is out of its range the bit pattern is preserved and the appropriate bits are assigned The following expression sets the toaster field of the kitchen structure to 0 because only the least significant bit is assigned to the toaster field kitchen toaster 2 Bit Fields under the align Compiler Option Bit fields are also subject to the qalign compiler option The default alignment is qalign power When it is in effect bit fields are aligned as described in Alignment of Bit Fields in S
267. ding operations are required by the C language but are not necessary for correct program execution Rounding operations are still inserted when double precision results are stored into single precision memory locations The hssngl option retains the results of floating point expressions in double precision when the original program would have rounded those results to single precision The retained double precision results are then used in later expressions instead of the rounded results The program results may be more accurate because of the increased precision and program execution may be faster because rounding operations have been omitted Rounding operations are still necessary in cases where a floating point result is stored into a single precision variable The result must be rounded to detect a single precision floating point overflow or underflow In some cases program optimization can remove store operations from a program The hssngl option allows the rounding operation that accompanied the original store to be removed also When the hssngl option can retain such a result in double precision an exception can be avoided The hssngl option is safe for all types of programs because it can only increase the precision of floating point computations in a program 28 C for AIX User s Guide Use the qfloat hssngl option with the O option but not with the qfloat rndsngl option Related Reading qfloat nans The qfloat nans opti
268. directories for precompiled header files with the qgenpcomp and qusepcomp compiler options This allows you to create more than one initial sequence and further improve your compile time When you use precompiled header files the following restrictions apply e To create a precompiled header file the compiler process must have write permission to the directories you specify or to the current working directories if none are specified e To use a precompiled header the compiler process must have read permission for that file e Precompiled header files do not appear in any listing files Related Reading Minimizing the Size of Object Files To minimize the size of object files you can specify the qcompact option Using this option may increase execution time Related Reading 36 C for AIX User s Guide Chapter 5 Program Parallelization The compiler offers you two methods of implementing shared memory program parallelization These are e Automatic and explicit parallelization of countable loops using IBM pragma directives e Program parallelization using pragma directives compliant to the OpenMP Application Program Interface specification All methods of program parallelization are enabled when the qsmp compiler option is in effect without the omp suboption You can enable strict OpenMP compliance with the qsmp omp compiler option but doing so will disable automatic parallelization Parallel regions of program
269. dix D Preprocessor Directives and Related Information 359 Meme see __TIMESTAMP__ A character string literal containing the date and time when the source file was last modified The value of _ TIMESTAMP __ changes as the compiler process any include files that are part of your source program The date and the time are in the form Day Mmm dd hh mm ss yyyy where Day Represents the day of the week Mon Tue Wed Thu Fri Sat or Sun Mmm Represents the month in an abbreviated form Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov or Dec dd Represents the day of the month If the day is less than 10 the first d is a blank character Represents the hour Represents the minutes Represents the seconds yyyy Represents the seconds The date and time are always set to the system date and time Note You cannot use the U option to undefine a predefined macro name C for AIX Predefined Preprocessor Macros C Defined if the compiler is invoked to compile in 64 bit mode This macro should not be user defined or redefined Defined if the operating system is AIX version 3 2 or higher Defined if the operating system is AIX version 4 1 or higher Defined if the operating system is AIX version 4 3 or higher ANSI Allows only language constructs that conform to ANSI C standards Defined using the pragma langlvl directive or the qlanglvl compiler option _ARCH Indicates that the compiler generates code to run on
270. double double double float __fabss float double __ fabs double float __fnabss float double __fnabs double void __dcbt void void __dcbz void void __ trap int Return Value or Action Performed __fmadds a x y a x y __fmadd a x y a x y __fmsubs a x y a x y __fmsub a x y a x y __fnmadds a x y a x y __fnmadd a x y a x y __fnmsubs a x y a x y __fnmsub a x y a x y __fsarts x square root of x __fsaqrt x square root of x __frsarte x estimate of 1 0 sqrt x __ fres x estimate of 1 0 x if a gt 0 0 then __fsels a x y x else __ fsels a x y y if a gt 0 0 then __fsel a x y x else _ fsel a x y y _ fabss x x __ fabs x x __fnabss x x __fnabs x x Data Cache Block Touch Loads the block of memory containing the specified address into the data cache Data Cache Block set to Zero Sets the specified address in the data cache to zero 0 Trap if the parameter is not zero 435 Return Value or Action Performed Name Prototype Trap if the parameter is not zero __trapd void __trapd long long Related Reading 436 cC for AIX User s Guide Appendix H RISC System 6000 Alignment Rules On the RISC System 6000 system an aggregate is aligned according to its most strictly aligned member With
271. ds xlsmp and thread safe versions of all default run time libraries are linked to the resulting executable Related Reading source Option Type Default Value pragma options Syntax qsource qnosource SOURCE NOSOURCE Purpose Produces a compiler listing and includes source code Notes The qnoprint option overrides this option Parts of the source can be selectively printed by using pairs of pragma options source and pragma options nosource preprocessor directives throughout your source program The source following pragma options source and preceding pragma options nosource is printed Example The following code causes the parts of the source code between the pragma options directives to be included in the compiler listing pragma options source Source code to be included in the compiler listing 322 C for AIX User s Guide is bracketed by pragma options directives pragma options nosource To compile myprogram c to produce a compiler listing that includes the source for myprogram c enter xlc myprogram c qsource Related Reading spill Option Type Default Value pragma options spill 512 SPILL size Syntax qspill size SPILL size Purpose Specifies the register allocation spill area as being size bytes Notes lf your program is very complex or if there are too many computations to hold in registers at one time and your program needs temporary storage you might need to
272. ds Reference If you do not specify the o option the output file generated by the M option is created in the current directory It has a u suffix For example the command xlc M person_years c produces the output file person_years u A u file is created for every input file with a c or i suffix Output u files are not created for any other files For example the command xlc M conversion c filter c lib libm a produces two output files conversion u and filter u and an executable file as well No u file is created for the library If the current directory is not writable no u file is created If you specify ofile_name along with M the u file is placed in the directory implied by ofile_name For example for the following invocation xlc M c t c o tmp t o places the u output file in tmp t u Format of the Output File The output file contains a line for the input file and an entry for each include file It has the general form file_name o file_name cfile_name o include file name Include files are listed according to the search order rules for the include preprocessor directive described in EDire i the include file is not found it is not added to the u file Files with no include statements produce output files containing one line that lists only the input file name Related Reading 294 C for AIX User s Guide ma Option Type Default Value pragma options a Syntax ma Purpose Su
273. e packed Related Reading Bit fields are packed into a 1 byte space Bit fields that cross byte boundaries are forced to start at the next available byte boundary A bit field with a width of O zero forces the next member to start at the next byte boundary If the zero width bit field is already at a byte boundary the next structure member starts there A non bit field member following a bit field is aligned on the next byte boundary In the following example the bit fields in the structure order are aligned according to the qalign packed option pragma options align packed struct order char a int b 10 int c 12 int d 6 int 0 inte 1 char f E The following figure shows the layout of order The shaded areas are padding Bit Field Size 8 2 8 4 6 1 alele cldije f in 23 4 5 6 7 ET T a c c c e alalald a la e TT TITT Because bit field c is longer than 1 byte and cannot straddle the boundary between bytes 2 and 3 it must start at byte 3 Likewise field d cannot cross the byte boundary between bytes 4 and 5 it is forced to start at byte 5 The zero width bit field between field d and field e forces bit field e to start at byte 6 Examples of Structure Declaration and Use The following program finds the sum of the integer numbers in a linked list xx Example program illustrating structures using linked lists include lt stdio h gt struct record Chapter 6 The C Languag
274. e union char birthday 9 int age float weight people 23 07 57 Defining a Union Type and a Union Variable To define union type and a union variable in one statement put a declarator after the type definition The storage class specifier for the variable must go at the beginning of the statement Alignment of Unions The rules for alignment of structures and structure members apply to unions with the following exception when the qalign twobyte option is specified a union whose largest element is a bit field of width 16 or less has a size of 2 bytes If the width of the bit field is greater than 16 the size of the union is 4 bytes Anonymous Unions Union can be declared without declarators if they are members of another structure or union Unions without declarators are called anonymous unions Note Annonymous unions are not part of the the ANSI C language standard and are supported by C for AIX in extended compiler mode only Members of an anonymous union can be accessed as if they were declared directly in the containing structure or union For example given the following structure struct s int a union int Ds float c E no declarator kurt you can make the following statements kurt a 5 kurt b 36 You can also declare an anonymous union by 1 Creating a typedef and using the typedef name without a declarator typedef union int a int b UNION T 104 C for AIX Users Guide
275. e 1 amp amp 4 evaluates to O 130 C for AIX User s Guide Logical OR The logical OR operator indicates whether either operand has a nonzero value If either operand has a nonzero value the result has the value 1 Otherwise the result has the value 0 Both operands must have a scalar type The usual arithmetic conversions on each operand are performed The result has type int and is not an Ivalue Unlike the bitwise inclusive OR operator the operator guarantees left to right evaluation of the operands If the left operand has a nonzero value the right operand is not evaluated The following examples show how expressions that contain the logical OR operator are evaluated Expression Result 1 0 1 1 4 1 ollo o The following example uses the logical OR operator to conditionally increment y x y The expression y is not evaluated when the expression x evaluates to a nonzero quantity Note The logical OR should not be confused with the bitwise OR operator For example 1 4 evaluates to 1 while 1 4 evaluates to 5 Related Reading Conditional Operator A conditional expression is a compound expression that contains a condition operand1 an expression to be evaluated if the condition has a non zero value operand2 and an expression to be evaluated if the condition has the value 0 operand3 Conditional expressions have right to left associativity The left operand
276. e 101 int number struct record next_num i int main void Struct record namel name2 name3 struct record recd_ pointer amp namel int sum 0 namel number 144 name2 number 203 name3 number 488 namel next_num amp name2 name2 next_num amp name3 name3 next_num NULL while recd_ pointer NULL sum recd pointer gt number recd pointer recd_pointer gt next_num printf Sum d n sum return Q The structure type record contains two members the integer number and next_num which is a pointer to a structure variable of type record The record type variables namel name2 and name3 are assigned the following values Womb atu The variable recd_pointer is a pointer to a structure of type record It is initialized to the address of namel the beginning of the linked list The while loop causes the linked list to be scanned until recd_pointer equals NULL The statement recd_ pointer recd_pointer gt next_num advances the pointer to the next object in the list The following example shows how to define and initialize a structure within a structure struct client char name struct info int age int weight pers_info child Bob 3 31 initialization Related Reading Estruct Structures an page 95 102 C for AIX Users Guide union Unions A union is an object that can hold any one of a set of named members The members of the named set
277. e Placement in Source langlvl langlvl Before any statements in the source file isolated call isolated call Before any calls to the listed functions Note pragma options arch suboption is not supported in source files Related Reading pragma reachable Preprocessor Directive The pragma reachable directive takes a function name and declares that the point in the program after that function can be the target of a branch from some unknown location In other words the instruction after the specified function can be reached from a program point other than the return statement in the named function Pe pragma reachable functian T T J a function If the specified function is not found a warning message is shown Related Reading pragma strings Preprocessor Directive Specifies that the compiler can place strings into read only memory or must place strings into read write memory Pe pragma strings ey cara i 4 readonty This pragma must appear before any statements in a source file The default for ansi mode is readonly The default for extended mode is writable The specification writable is supported for portability between releases of the XL C compiler product 376 C for AIX User s Guide This pragma has the same effect as the qro compiler option Related Reading Preprocessor Macro Operators This page lists and briefly describes preprocessor macro operators available to
278. e balancing makes all operands have the same data type If both of the operands do not have the same size data type the compiler converts the value of the operand having the smaller type to a value having the larger type For example if the operand count has type int and the operand maximum has type long the compiler converts the value of count to type long Type balancing does not affect the sign of the value Sign BalancingSign balancing makes both operands have the same data type signed or unsigned If one operand has an unsigned type the compiler converts the other operand to that unsigned type Otherwise both operands remain signed Assignment ConversionAn assignment conversion makes the value of the right operand have the same data type as the left operand Only the following assignment type combinations are supported by the language Type of Left Operand Right Operand Any arithmetic type Any arithmetic type Pointer to type Pointer to type or the NULL pointer Structure of type Structure of type Union of type Union of type Explicit Conversions page hed describes how the compiler performs conversions from one arithmetic type to another arithmetic type Explicit ConversionsWhen the compiler converts the values of one data type to the value of another data type the compiler usually performs one of the following conversions Reduction conversions Change the data type of a value to a smaller size data type for example a
279. e comma before the ellipsis is optional Chapter 6 The C Language 141 Parameter promotions are performed as needed but no type checking is done on the variable arguments You can declare a function with no arguments in two ways int f void x f takes no parameters x int f f takes any number or type or parameters x An empty argument declaration list or the argument declaration list of void indicates a function that takes no arguments void cannot be used as an argument type although types derived from void such as pointers to void can be used In the following example the function f takes one integer parameter and returns no value while g expects no parameters and returns an integer void f int int g void Function Body The body of a function is a block statement The following function body contains a definition for the integer variable big_num an if else control statement and a call to the function printf void largest int numl int num2 int big_num if numl gt num2 big num numl else big num num2 printf big num d n big num Related Reading a Ot Of Dd OE J Of g On Oade rd AN Examples of Function Definitions In the following example ary is an array of two function pointers Type casting is performed to the values assigned to ary for compatibility include lt stdio h gt int funcl void void func2 double a int main void 142 C for
280. e compiler will by default compile and link applications conforming to the current Posix threads standards 6 C for AIX User s Guide Types of Input Files You can input the following types of files to the C for AIX compilers C Source Files Preprocessed Source Files Object Files Assembler Files Nonstripped Executable Files Related Reading These are files containing a C source module The source file must have a c lowercase c suffix for example mysource c The compiler will also accept source files with the i suffix This extension designates preprocessed source files The compiler processes the source files in the order in which they appear If the compiler cannot find a specified source file it produces an error message and the compiler proceeds to the next specified file However the link editor will not be run and temporary object files will be removed Your program can consist of several source files All of these source files can be compiled at once using only one invocation of xic Although more than one source file can be compiled using a single invocation of the compiler you can specify only one set of compiler options on the command line per invocation Each distinct set of command line compiler options that you want to specify requires a separate invocation By default the xic command preprocesses and compiles all the specified source files Although you will usually want to use this default you
281. e complete description of a function A function definition contains an optional storage class specifier an optional type specifier a function declarator parameter declarations and a block statement the function body function prototype A function declaration that provides type information for each parameter It is the first line of the function header followed by a semicolon It is required by the compiler when the function will be declared later so type checking can occur function scope Labels that are declared in a function have function scope and can be used anywhere in that function G global scope See 494 global variable A symbol defined in one program module that is used in other independently compiled program modules H header file A file that contains declarations used by a group of functions or users hexadecimal A system of numbers to the base sixteen hexadecimal digits range from O zero through 9 nine and A ten through F fifteen hexadecimal constant A constant usually starting with special characters that contains only hexadecimal digits The special characters are x 0x or OX I O Stream Library A class library that provides the facilities to deal with many varieties of input and output identifier A name that refers to a data object An identifier contains some combination of letters digits and underscores but its first character cannot be a digit if statement A conditional statem
282. e declarator If a parameter is not declared it has type int char and short parameters are widened to int and float to double No type checking between the argument type and the parameter type is done for nonprototyped functions As well there are no checks to ensure that the number of arguments matches the number of parameters Each value that a function receives should be declared in a parameter declaration list for nonprototype function definitions that follows the declarator A parameter declaration determines the storage class specifier and the data type of the value The only storage class specifier allowed is the register storage class specifier Any type specifier for a parameter is allowed If you do not specify the register storage class specifier the parameter will have the auto storage class specifier If you omit the type specifier and you are not using the prototype form to define the function the parameter will have type int int func i j i and j have type int You cannot declare a parameter in the parameter declaration list if it is not listed within the declarator Ellipsis and void An ellipsis at the end of a parameter declaration indicates that the number of arguments is equal to or greater than the number of specified argument types At least one parameter declaration must come before the ellipsis Where it is permitted an ellipsis preceded by a comma is equal to a simple ellipsis int fintes Th
283. e deleted from the calling function where appropriate Instructions can be reordered with more freedom resulting in fewer pipeline delays and faster execution in the processor Note that instruction reordering might yield code with more values in general purpose and or floating point registers maintained across the isolated call When the isolated call is not located in a loop the overhead of saving and restoring extra registers might not be worth the savings that result from deleting the storage references Functions specified in the identifier are permitted to examine external objects and return results that depend on the state of the runtime environment The functions can also modify the storage pointed to by any pointer arguments passed on to the function that is calls by reference Do not specify a function that calls itself or relies on local static storage Listing such functions in the pragma isolated_call directive can give unpredictable results The qisolated_call compiler option has the same effect as this pragma The qignprag compiler option causes aliasing programs to be ignored Use this option to debug applications containing the pragma isolated_call directive Related Reading Example of the pragma isolated_call Preprocessor Directive The following example shows the use of the pragma isolated_call directive Because the function this_function does not have side effects a call to it will not change the value of the extern
284. e directory where the current file resides qidirfirst has no effect on the search order for the include lt file_name gt directive qidirfirst is independent of the qnostdinc option which changes the search order for both include file name and include lt file_ name gt The search order of files is described in EDire The last valid pragma option NOJIDIRFirst remains in effect until replaced by a subsequent pragma option NO IDIRFirst Example To compile myprogram c and search usr tmp myinclude for included files before searching the current directory where the source file resides enter xlc myprogram c I usr tmp myinclude qidirfirst Appendix A Compiler Options 273 Related Reading ignerrno Option Type Default Value pragma options aopton e Syntax qignerrno qignerrno Purpose Allows the compiler to perform optimizations that assume errno is not modified by system calls Notes Library routines set errno when an exception occurs This setting and subsequent side effects of errno may be ignored by specifying qignerrno Related Reading ignprag Option Type Default Value pragma options Syntax qignprag suboption IGNPRAG suboption Purpose Instructs the compiler to ignore certain pragmas Notes Suboptions are all Equivalent to selecting all options described below disjoint Ignores all pragma disjoint directives in the source file isolated Ignores all pragma
285. e encoded such that the first character identifies the form of the multibyte character Any character is valid in the remaining bytes 2 2 1 2 A character in the execution character set contains 8 bits 2 2 4 2 The mapping of members of the source character set in character and string literals to members of the execution character set is one to one 3 1 3 4 The same code set is used for both source and execution set 3 1 3 4 The lowest 4 bytes represent character constants when 3 1 3 4 e An integer character constant contains a character or escape sequence not represented in the basic execution character set e A wide character constant contains a character or escape sequence not represented in the extended character set e An integer character constant contains more than one character e A wide character constant contains more than one multibyte character The name of the locale used to convert multibyte characters into corresponding wide characters codes for a wide character constant is user defined 3 1 3 4 The default equivalent type of a plain char is unsigned char 3 2 1 1 The chars option sets the sign type of characters Related Reading Implementation Dependency Integers F 3 5 The following table shows the storage occupied and the range of various integer types 3 1 2 5 a S E O wwo o S O M ee Ba D e a a unsigned long long 64 O to 18446744073709551615 When an integer is converte
286. e first compile step Assume there exists two functions trace_error and debug _ dump which are rarely executed xlc c 03 c qipa noobject xlc c 03 0 qipa lowfreq trace_error debug_dump If a given compiler option is specified at both compile and link time with differing settings the link time option settings will generally prevail In the example below the O3 option used at link time along with other settings implied by O3 overrides the O2 option used at compile time xlc c 02 c qipa noobject xlc c 03 0 qipa lowfreq trace_error debug_dump Related Reading isolated_call Option Type Default Value pragma options Syntax qisolated_call function_name ISOLATED CALL function_name 284 C for AIX User s Guide Purpose Specifies functions in the source file that have no side effects Notes function_name Is the name of a function that does not have side effects or does not rely on functions or processes that have side effects Side effects are any changes in the state of the runtime environment Examples of such changes are accessing a volatile object modifying an external object modifying a file or calling another function that does any of these things Functions with no side effects cause no changes to external and static variables function_name can be a list of functions separated by colons Marking a function as isolated can improve the runtime performance of optimized code by indicating
287. e first step from the point at which the macro was replaced as if it were part of the original program 4 When the entire program has been preprocessed the result is scanned again by the compiler as in the first step The second and third steps do not apply here since there will be no macros to replace Constructs generated by the first three steps that resemble preprocessing directives are not processed as such It is in the third and fourth steps that the text of adjacent but previously separate tokens may be combined to form new tokens The character for line continuation is accepted only in string and character literals and on preprocessing directives Constructs such as if 0 unterminated endi f define US Unterminating string char s US terminated now will not generate diagnostic messages since the first is an unterminated literal in a FALSE block and the second is completed after macro expansion However char s US will generate a diagnostic message since the string literal in US is not completed before the end of the line Empty character literals are allowed The value of the literal is zero The token must appear in the first column of the line The token immediately following is available for macro expansion The line can be continued with only if the name of the directive and in the following example the has been seen define f a b a b f 1 2 accepted define f a b a b F 1 2
288. e following fragment shows an example of a getmore_ fn static void getmore fn Heap t uh size_t length int clean char newblock round the size up to a multiple of 64K xlength length 65536 65536 65536 clean BLOCK CLEAN mark the block as clean return newblock return new memory block Shrinking Your Heap To coalesce the heap return all blocks in the heap that are totally free to the system use _uheapmin _uheapmin works like _heapmin except that you specify the heap to use When you call uheapmin to coalesce the heap or udestroy to destroy it these functions call your release fn to return the memory to the system Again it is up to you how you implement this function Your release_fn must have the following prototype void release fn Heap _t uh void block size_t size Where uh identifies the heap to be shrunk The pointer block and its size are passed to your function by _uheapmin or udestroy Your function must return the memory pointed to by block to the system For example Chapter 7 Writing C Programs 189 static void release fn Heap t uh void block size_t size free block return Notes 1 _udestroy calls your release fn to return all memory added to the uh heap by your getmore_fn or by _uaddmem However you are responsible for returning the initial block of memory that you supplied to ucreate 2 Because a fixed size heap has no release fn uheapmin
289. e in AIX 4 2 to int type in AIX 4 3 The change in types may cause compile time errors in your programs MB CUR_MAX has changed from int to size_t in AIX 4 3 MB CUR_MAX is a macro defined in stdlib h that calls _getmbcurmax This function now returns size_t which has always been unsigned long In AIX 4 2 it was prototyped to return an int setlocale in 64 bit mode If you have user locales defined you must recompile them in 64 bit mode using localedef This generates 32 bit and 64 bit versions of your locale file Otherwise calling setlocale in 64 bit mode will not find the user defined locale file However localedef in AIX 4 3 supports only the charmap that is supplied with the AIX 4 3 distribution If you need the charmaps from an older AIX distribution you must explicitly copy them into your directory before using localedef with your custom locale definition file In addition localedef by default is set up to use bin cc and usr bin cc The C for AIX compiler does not create links in usr bin or bin by default Since localedef requires the use of a 64 bit compiler you need to run usr vac bin replaceCSet to create links pointing to the C for AIX product Invoke localedef then execute restoreCSet to restore the links as they were before The make tool does not discriminate between object formats The make tool only discriminates on the timestamp of files The only case where this can cause problems is when you try to add same nam
290. e invocation commands with the 128 suffix xlc128 or cc128 You can also manually link to the 128 bit versions of the libraries using the lkey option as shown in the following table Default 64 bit long double 128 bit long double Library Form of the lkey option Form of the lKkey option Do complexi 28 Linking without the 128 bit versions of the libraries when your program uses 128 bit long doubles for example if you specify qldbl128 alone may produce unpredictable results The qldbl128 option defines _ LONGDOUBLE128 The pragma options directive must appear before the first C statement in the source file and the option applies to the entire file Example To compile myprogram c so that long double types are 128 bits enter xlc myprogram c qldb1128 1C128 Or xlc128 myprogram c Fora escriptor of the 128 bit long double refer to Related Reading libansi Option Type Default Value pragma options a a Syntax qlibansi qnolibansi Purpose Assumes that all functions with the name of an ANSI C library function are in fact the system functions 290 C for AIX User s Guide Notes This will allow the optimizer to generate better code because it will know about the behavior of a given function such as whether or not it has any side effects Related Reading linedebug Option Type Default Value pragma options Syntax qLINEDebug qNOLINEDebug Purpose Generates line number and source
291. e is valid For example define M 1 not allowed def Chapter 6 The C Language 165 ine M1 not allowed define M 1 allowed dfine M 1 equivalent to dfine M 1 even though dfine is not valid Following are the preprocessor directive differences between classic mode and ansi mode directives not listed here behave similarly in both modes ifdet ifndef When the first token is not an identifier no diagnostic message is generated and the condition is FALSE else When there are extra tokens no diagnostic message is generated endif When there are extra tokens no diagnostic message is generated include The lt and gt are separate tokens The header is formed by combining the spelling of the lt and gt with the tokens between them Therefore and are recognized as comments and are always stripped and that and do begin literals within the lt and gt Note In C programs style comments are only valid when cpluscmt is specified line The spelling of all tokens which are not part of the line number form the new file name These tokens need not be string literals error Not recognized in classic mode define A valid macro parameter list consists of zero or more identifiers each separated by zero or more commas The commas are ignored and the parameter list is constructed as if they were not specified The parameter names need not be unique If there is a conflict
292. e larger data types where possible qopt longlong Allows long long types in your program flag Creates an output file that contains targets suitable for inclusion in a description file for the AIX make command 222 C for AIX User s Guide Substitutes inline code for calls to function alloca as if pragma alloca directives are in the source code flag nomacpsir Converts Pascal string literals into null terminated strings where the first byte contains the length of the string maf Specifies whether the floating point multiply add instructions are to be generated Creates an output file that contains targets suitable for inclusion in a description file for the AIX make command nomaxerr Instructs the compiler to halt compilation when a specified number of errors of specified or greater severity is reached Limits the amount of memory used for local tables of specific memory intensive optimizations maxmem 2048 nombcs Use the qmbcs option if your program contains multibyte characters Suppresses listings nooptimize Optimizes code at a choice of levels during compilation qopt flag flag Specifies a name or directory for the output executable file s created either by the compiler or the linkage editor noonce Avoids including a header file more than once even if it is specified in several of the files you are compiling flag Preprocesses the C source
293. e list cannot refer to any of the following e A member of a structure or union e A structure union or enumeration tag e An enumeration constant e A typedef name 366 C for AIX User s Guide e A label The identifiers must be declared before they are used in the pragma A pointer in the identifier list must not have been dereferenced or used as a function argument before appearing in the directive The qignprag compiler option causes aliasing pragmas to be ignored Use this option to debug applications containing the pragma disjoint directive Related Reading Example of the pragma disjoint Preprocessor Directive The following example shows the use of pragma disjoint int a b ptr a ptr pb pragma disjoint ptr_a b ptr_a never points to b pragma disjoint ptr_b a ptr_b never points to a one_function b 6 xptr_a 7 Assignment will not change the value of b another_function b Argument b has the value 6 Because external pointer ptr_a does not share storage with and never points to the external variable b the assignment of 7 to the object that ptr_a points to will not change the value of b Likewise external pointer ptr_b does not share storage with and never points to the external variable a The compiler can assume that the argument to another function has the value 6 and will not reload the variable from memory Related Reading pragma execution_frequency Preprocessor Direct
294. e of the constant is determined in the following way 1 An equal sign and a constant expression after the enumeration constant gives an explicit value to the constant The identifier represents the value of the constant expression 2 If no explicit value is assigned the leftmost constant in the list receives the value zero 0 3 Identifiers with no explicitly assigned values receive the integer value that is one greater than the value represented by the previous identifier Each enumeration constant has an integer value Use an enumeration constant anywhere an integer constant is allowed Each enumeration constant must be unique within the scope in which the enumeration is defined In the following example the declarations of average on line 4 and of poor on line 5 cause compiler error messages 82 C for AIX User s Guide func enum score poor average good enum rating below average above int poor Dor WNYM Fe Defining Enumeration Variables An enumeration variable definition contains an optional storage class specifier a type specifier a declarator and an optional initializer The type specifier contains the keyword enum followed by the name of the enumeration data type You must declare the enumeration data type before you can define a variable having that type The initializer for an enumeration variable contains the symbol followed by an expression The initializer expression must evaluate to an
295. e the volatile qualifier Similarly if you specified the const keyword instead of volatile only the variable object receives the const qualifier Expression Operators Operator Precedence and Associativity Table The following table lists the C language operators in order of precedence and shows the direction of associativity for each operator The primary operators have the highest precedence The comma operator has the lowest precedence Operators that appear in the same group have the same precedence Unary amp type name sizeof Multiplicative ay m ewen wo fa e T aon o rma e ee Cee hnk Chapter 6 The C Language 117 Related Reading Primary Operators Parentheses Used for Expression Grouping Use parentheses to explicitly force the order of expression evaluation The following expression does not contain any parentheses used for grouping operands and operators The parentheses surrounding weight zipcode are used to form a function call Note how the compiler groups the operands and operators in the expression according to the rules for operator precedence and associativity discount item handling weight zipcodej lt 10 item The following expression is similar to the previous expression but it contains parentheses that change how the operands and operators are grouped discount item handling weight zipeode lt 10 item In an expression that contains both ass
296. e to change your source code in order for debug memcpy to verify the heap Appendix F C for AIX Debug Functions 413 Note The qheapdebug option maps all calls to other string functions and all calls to memory management functions including a heap specific version to their debug counterparts To prevent a call from being mapped parenthesize the function name Return Value _debug_memcpy returns a pointer to dest Example This example contains a programming error On the memcpy used to initialize the target location the count is more than the size of the target object and the memcpy operation copies bytes past the end of the allocated object include lt stdlib h gt include lt string h gt include lt stdio h gt define MAX_LEN 10 int main void char source target target char malloc MAX_ LEN memcpy target This is the target string 11 printf Target is s n target return 0 RR k k EKER ERR KR KEKE k k k ERK ERK ER RE RRR RK ERK ER KER KKK KEKE EKER KEK ERK ERE RRR ERK KK k Kk Kk k k k The output should be similar to End of allocated object 0x00073c80 was overwritten at 0x00073c8a The first eight bytes of the memory block in hex are 5468697320697320 This memory block was re allocated at line number 11 in memcpy c Heap state was valid at line 11 of memcpy c Memory error detected at line 12 of memcpy c KKK KKK KEK KERR KK EKER KER KKK EKER KERR RK ERK ER KEE RRR KER KER RRR K
297. e28ee et eeeeneeeeeeeoateaweaeaeesa se amp C0 Strict INOUCHON s x a s a s s eam fa Piee rona dog nania w Or SYMON e ek s a wk ee 2 ek O Oe be we o a a Oh a o a oe a E ROA SUDPICSS s a s p d s a SHS we Ba eo ew dania 4 Se HR Se He GE HCO Feaaweespteaetaeeee sh eee eee ee ee eee ee eee ee ee IA0SIZe ew ee eee eee ee ee eee eee eee ee ee eee oe ee we oeg DaD ss a a se eae eee Ae ee ee ee ee ee eee ee eb op Ee me amp 2 OU redadeg s a ww de Bae ee ee Re ee ee eee Be te ee ee ee Bd UNG a s oo s s ete Ree Ree eee Ae ese he a bo eB Oe eee me ee Oe Oe a Ol Oeeee eee ewe Pe ee ee Re eee eee ee ee ee ke ee eee eee unroll amp eweeeeaeaeeeeeewee eee to te ee me ew ee we amp wo 93 UDCOMV 2 ww ee Ym ee we Fo we Foe ee ee ee se oe ae oe oe we F SOF USCDCOMID s ek s s r Se be oe eH Rae eee ee ee oe kOe ee we ee BCD Vow hee eee ete ee eee bee be eee fe eee te eo eS ee a CO We szerekre s gnoned adaa tenet eaten Beene ee et amp 2 0C0 Web eee e a a a a a a e teeth ee Rae ew eek eee ee me ee Or Walliot amp s d s e ci eee ee eee FBR eH Hh ee ee ee ow fe me HOC MGalla e e eepeehadeheePeeeaeaneeweeeoeouaetsaeeoe itz amp 5 O00 MIG 2 es Sete eeaebeehasweeuepetzreteee eB eee obese 2 es E E O Veaaueeaneeeeeaneheavpresaeeeeueeeees tee paz e amp amp S 2 Ged Appendix B 32 bit to 64 bit Migration Considerations 341 X C for AIX Users Guide Appendix C Operating System Migration Considerations
298. ead Some programs might check portions of their results by comparing those results with values computed on other systems Again the rndsngl option may be required to duplicate the previous results and to have such programs report correct execution Programs checking double precision results may also require the nomaf option Related Reading qfittrap The IEEE standard for floating point arithmetic specifies that five types of exceptions be signalled when detected e overflow e underflow e division by zero e invalid operation e inexact By default the signalling of an exception involves setting a status flag and continuing The standard also allows for an exception to generate a trap and invoke a handler routine specified by the user The flttrap option directs the compiler to produce code that generates a TRAP signal to flag the occurrence of any enabled floating point exception Exception types can be specified with the flttrap option Each of the five exception types is controlled by a separate suboption 30 C for AIX User s Guide OVerflow Generates code to detect and trap floating point overflow UNDerflow Generates code to detect and trap floating point underflow ZEROdivide Generates code to detect and trap floating point division by zero INValid Generates code to detect and trap floating point invalid operation exceptions INEXact Generates code to detect and trap floating point inexact exceptions The exception
299. ect file file_name o for each valid source file file_name c or file_name i The c option is overridden if either the E P or qsyntaxonly options are specified The c option can be used in combination with the o option to provide an explicit name of the object file that is created by the compiler Example To compile myprogram c to produce an object file myfile o but no executable file enter the command xlc myprogram c c To compile myprogram c to produce the object file new o and no executable file enter xlc myprogram c c 0 new o 242 C for AIX User s Guide Related Reading cache Option Type Default Value pragma options a E Syntax qcache assoc number auto cost cycles level level line bytes size Kbytes aie lal Dies sss Purpose Use this option to describe the cache configuration for a specific target execution machine if different from the compiling machine The compiler uses this configuration information to optimize program performance particularly loop operations that can be structured or blocked to maximize effective use of the data cache on the target execution machine Notes The qcache option has an effect only if you also specify the qipa O4 O5 or qsmp options Suboption Description assoc number Specifies the set associativity of the cache where number can be 0 Direct mapped cache 1 Fully associative cache n gt 1 n way set associative cache auto Specif
300. ed Heap Specific Debug Functions The heap specific functions also have debug versions that work just like the regular debug versions Use these functions to allocate and free memory from the user created heap you specify and also provide information that you can use to debug memory problems in your own heaps Use the qheapdebug compiler option to automatically map all calls to the regular memory management functions to their debug versions You can also call the debug versions explicitly Note If you parenthesize the calls to the regular memory management functions they are not mapped to their debug versions The names of the heap specific debug versions are prefixed by debug_u for example debug_umal loc and they are defined in lt umalloc h gt The functions provided are e debug _ucalloc e debug uheapmin e _debug_umalloc e _udump_ allocated e _udump allocated delta e _uheap_ check The debug _umalloc function sets the memory areas they affect to a specific repeating fill pattern See j for more information There are no heap specific debug versions of debug realloc or debug free These functions always determine which heap memory is allocated from and can be used with both user created and runtime memory heaps Chapter 7 Writing C Programs 181 Related Reading Managing Memory with Multiple Heaps C for AIX lets you create and use your own pools of memory called heaps You can use your own heaps in place
301. ed parenthesize the function name A heap specific version of this function _debug_uheapmin is also available debug heapmin always operates on the default heap Return Value If successful debug heapmin returns 0 otherwise it returns 1 Example This example allocates 10000 bytes of storage changes the storage size to 10 bytes and then uses _debug_heapmin to return the unused memory to the operating system The program then attempts to 410 C for AIX Users Guide overwrite memory that was not allocated When _debug_heapmin is called again heap check detects the error generates several messages and stops the program Note You must compile this example with the qheapdebug option to map the _heapmin calls to _debug_heapmin include lt stdlib h gt include lt stdio h gt int main void char ptr Allocate a large object from the system if NULL ptr char malloc 100000 puts Could not allocate memory block exit EXIT_FAILURE ptr charx realloc ptr 10 _heapmin No allocation problems to detect x ptr 1 a Overwrite memory that was not allocated x _heapmin This call to heapmin invokes _heap_ check puts debug heapmin did not detect that a non allocated memory block was overwritten return 0 kkkkkkkkkkkkkkkk kkk ERE ERK kk kkk KER KEK KER KERR kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk Possible output is Header information of object 0x000738b0 was
302. ed 32 and 64 bit objects into the archive Running make first in 32 bit mode then in 64 bit mode will not update the 2nd object Make only checks the timestamp of the first object it finds with the correct name int64 is type defined in inttypes h If you use int64 as a variable name this is now a typedef in inttypes h Header file predefined types that are based on long There are many header file predefined types such as size_t and ptrdiff_t which remain the same type regardless of 32 or 64 bit compiler mode This presents a subtle opportunity for differences when compiling the same code in different mode of the compiler Although size_t remains the same type unsigned long the length of size_t will change between different modes of AIX This can cause library functions that return or take size_t to change behavior in 32 bit to 64 bit mode Specifically sizeof will return an 8 byte value in 64 bit and a 4 byte value in 32 bit mode The same applies to prtdiff_t which is signed long in both modes m n thread may exhaust memory rapidly The m n thread model is one of the 3 models used to map user threads to kernel threads Inthe m 1 model all user threads are mapped to one kernel thread and all user threads run on one virtual processor This is the traditional model on single threaded systems Inthe 1 1 model each user thread is mapped to one kernel thread and each user thread runs on one virtual processor POSIX 1003 1c Draft 7
303. ed Reading Example Using the do Statement The following statement prompts the user to enter a 1 If the user enters a 1 the statement ends If not it displays another prompt include lt stdio h gt int main void int replyl do printf Enter a 1 n scanf d amp replyl while replyl 1 return 0 Related Reading Expressions An expression statement contains an expression The expression can be null i 4 exGressign An expression statement evaluates the given expression which can then be assigned to a variable or used as an argument in a function call Some examples are printf Account Number n call to the printf x marks dollars exch rate assignment to marks difference lt 0 losses gain conditional increment switches flags BIT MASK assignment to switches Related Reading for A for statement lets you do the following e Evaluate an expression before the first iteration of the statement initialization Chapter 6 The C Language 149 e Specify an expression to determine whether or not the statement should be processed controlling part e Evaluate an expression after each iteration of the statement e Repeatedly process the statement if the controlling part does not evaluate to zero oe eel bee lel Lee expression expressions expression stetement pe Arguments to the for statement are expression1 Is the initialization exp
304. ed by the dynamic profiler must revert to being run in parallel mode again mSec can be specified using decimal places The default value for mSec is 5 milliseconds Appendix E Parallel Processing Facilities 403 Note You must use thread safe compiler mode invocations when compiling parallelized program code Related Reading OpenMP Run time Options for Parallel Processing OpenMP run time time options affecting parallel processing are specified in a set of OMP environment variables These environment variables which must be set before you run an application use syntax of form env_vartable option_and_args Parallelization run time options can also be specified by the XLSMPOPTS environment variable When OMP and XLSMPOPTS run time options conflict OMP options will prevail OpenMP run time options fall into different categories as described below Scheduling Algorithm Environment Variable OMP SCHEDULE algorithm This option specifies the scheduling algorithm used for loops not explictly assigned a 7 scheduling alogorithm with the omp schedule directive For example OMP_SCHEDULE guided 4 Valid options for algorithm are e dynamic n e guided n e runtime e static n If specified the value of n must be an integer value of 1 or greater The default is scheduling algorithm is static See oragqma page 389 for a description of these algorithms 404 C for AIX Users Guide Parallel Environment Enviro
305. ed with qipa and modify global variables and dummy arguments 282 C for AIX User s Guide filename Gives the name of a file which contains suboption information in a special format The file format is the following Comment attribute attribute name name missing attribute attribute exits name name lowfreq name name inline auto noauto inline name name from name name inline threshold unsigned integer inline limit unsigned integer list file name short long noinline noinline name name from name name level 0 1 2 partition small medium large unsigned integer where attribute is one of e exits e lowfreq e unknown e safe e isolated e pure Purpose Turns on or customizes a class of optimizations known as interprocedural analysis IPA Notes 1 IPA can significantly increase compilation time even with the qipa noobject option so using IPA should be limited to the final performance tuning stage of development Specify the qipa option on both the compile and link steps of the entire application or as much of it as possible You should compile at least the file containing main or at least one of the entry points if compiling a library While IPA s interprocedural optimizations can significantly improve performance of a program they can also cause previously incorrect but functioning programs to fail Listed below are some p
306. eed free ptr2 this call to free invokes _heap_check puts debug free did not detect that a freed memory block was overwritten return 0 EEk k k k k k k RE KER KK ERR ER RRR RR ERE RR KERR RK EKER RRR ER EKER ERE RK ERK kkk kk kkk KK KKK KKK The output should be similar to Free heap was overwritten at 0x00073890 Heap state was valid at line 12 of debug free c Memory error detected at line 14 of debug free c KK KK KKK EKER KR RK kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkx Appendix F C for AIX Debug Functions 409 Related Reading _debug_heapmin Free Unused Memory in the Default Heap Format include lt stdlib h gt also in lt malloc h gt int debug heapmin const char file size t line Language Level Extension _debug_heapmin is the debug version of _heapmin Like _heapmin it returns all unused memory from the default runtime heap to the operating system In addition debug heapmin makes an implicit call to heap check and stores the file name file and the line number line where the memory is returned This information can be used later by the _heap_check function To use _debug heapmin you must compile with the debug memory qheapdebug compiler option This option maps all heapmin calls to debug heapmin Note The qheapdebug option maps all calls to memory management functions including heap specific versions to their debug counterparts To prevent a call from being mapp
307. efined Truncate at decimal if result is too large for long result is undefined Truncate at decimal if result is too large for long long result is undefined Truncate at decimal if result is too large for long long result is undefined unsigned short unsigned long unsigned long From Preserve bit pattern sign function of sign bit lost signed char Preserve low order byte Preserve low order byte Preserve low order byte long long Preserve low order byte Sign extend to short and convert to unsigned short Preserve bit pattern sign function of sign bit lost Preserve low order byte Preserve low order byte Preserve low order byte Sign extend to int and convert int to unsigned int Sign extend to int and convert int to unsigned int Preserve bit pattern sign function of sign bit lost Preserve bit pattern sign function of sign bit lost Preserve low order byte Sign extend to long and convert long to unsigned long Sign extend to long and convert long to unsigned long Preserve bit pattern sign function of sign bit lost Preserve bit pattern sign function of sign bit lost Preserve low order byte Sign extend to long long and convert long long to unsigned long long Sign extend to long long and convert long long to unsigned long long Sign extend to long long and convert long long to unsigned long long Sign extend to
308. efore or after the function x is called y x i i 3 The result has the same type as the operand after integral promotion but is not an Ivalue The usual arithmetic conversions on the operand are performed 120 C for AIX Users Guide Unary Plus The unary plus operator maintains the value of the operand The operand can have any arithmetic type The result is not an lvalue The result of the unary plus expression has the same type as the operand after any integral promotions for example char to int The usual arithmetic conversions on the operand are performed Note Any plus sign in front of a constant is not part of the constant Unary Minus The unary plus operator negates the value of the operand The operand can have any arithmetic type The result is not an lvalue For example if quality has the value 100 quality has the value 100 The result of the unary minus expression has the same type as the operand after any integral promotions for example char to int The usual arithmetic conversions on the operand are performed Note Any plus sign in front of a constant is not part of the constant Logical Negation The logical negation operator determines whether the operand evaluates to O false or nonzero true The expression yields the value 1 true if the operand evaluates to 0 and the value O false if the operand evaluates to a nonzero value The operand must have a scalar data type but the re
309. elds the size in bytes of the operand Types cannot be defined in a sizeof expression Except in extended mode C the sizeof operation cannot be performed on e Abit field e A function e An array with unspecified dimensions e An incomplete type such as void The operand can be the parenthesized name of a type or expression The compiler must be able to evaluate the size at compile time The expression is not evaluated there are no side effects For example the value of b is 5 from initialization to the end of program runtime include lt stdio h gt int main void int b 5 sizeof bt When the compiler is in 32 bit mode the result is an integer constant When the compiler is in 64 bit mode the result is an unsigned long The size of a char object is the size of a byte For example if a variable x has type char the expression sizeof x always evaluates to 1 The result of a sizeof operation has type size_t which is an unsigned integral type defined in the lt stddef h gt header Header files are described in the AIX Version 4 Files Reference The size of an object is determined on the basis of its definition The sizeof operator does not perform any conversions If the operand contains operators that perform conversions the compiler does take these conversions into consideration The following expression causes the usual arithmetic conversions to be performed The result of the expression x 1 has type int if x has
310. elow q32 or q64 setting is incompatible with user selected qarch option Resolution q32 or q64 setting overrides qarch option compiler issues a warning message sets qarch option to com and sets qtune option to the qarch setting s default qtune value q32 or q64 setting is incompatible with user selected qtune option Resolution q32 or q64 setting overrides qtune option compiler issues a warning message and sets qtune option to the qarch setting s default qtune value gqarch option is incompatible with user selected qtune option Resolution Compiler issues a warning message and sets qtune tothe qarch setting s default qtune value Selected qarch or qtune options are not known to the compiler Resolution Compiler issues a warning message sets qarch to com and sets qtune to the qarch setting s default qtune setting The compiler mode 32 or 64 bit is determined by the OBJECT MODE environment variable or q32 q64 compiler settings Chapter 3 Using the C for AIX Compiler 15 Related Reading Acceptable Compiler Mode and Processor Architecture Combinations You can use the q32 q64 qarch and qtune compiler options to optimize the output of the compiler to Suit e the broadest possible selection of target processors e a range of processors within a given processor architecture family e a single specific processor Generally speaking the options do the following e q32sele
311. em to allocate storage for that variable and makes that variable accessible to the current block after its point of declaration K keyword A reserved C language identifier L label An identifier followed by a colon used to identify a statement in a program Usually the target of a goto or switch statement labeled statement A possibly empty statement immediately preceded by a label link To interconnect items of data or portions of one or more computer programs such as linking object programs by a linkage editor or linking data items by pointers linkage editor A program that resolves cross references between separately compiled object modules and then assigns final addresses to create a single relocatable load module If a single object module is linked the linkage editor simply makes it relocatable literal See Kad load module A computer program in a form suitable for loading into main storage for execution 494 C for AIX Users Guide local Pertaining to information that is defined and used only in one subdivision of a computer program local scope A name declared in a block has local scope and can only be used in that block long constant An integer constant followed by the letter I el or L lvalue An expression that represents an object A modifiable lvalue can be both examined and changed macro Call An identifier followed by a parenthetical list of arguments that the preprocessor replaces with the replacement c
312. endent only as long as exp evaluates to TRUE at run time Notes This pragma can be combined with the schedule pragma to select a specific parallel process scheduling algorithm For more information see the description for the schedule pragma Examples pragma ibm independent_loop applied to a for loop pragma ibm independent_loop for i 0 i lt N i ali i pragma independent_loop applied to a do while loop i 0 pragma ibm independent_loop do ali i irti while i lt N pragma independent_loop with if clause applied to a while loop i 0 pragma ibm independent_loop if dist gt N 2 while i lt N 2 ali alitdist itr Related Reading pragma ibm iterations Preprocessor Directive The iterations pragma specifies the approximate number of loop iterations for the chosen loop Syntax pragma ibm iterations iteration count lt countable for while do loop gt where iteration count represents a positive integral constant expression Notes The compiler uses the information in the teration count variable to determine if it is efficient to parallelize the loop 384 C for AIX User s Guide Related Reading pragma ibm parallel_loop Preprocessor Directive The parallel_loop pragma explicitly instructs the compiler to parallelize the chosen loop Syntax pragma ibm parallel _loop Lif exp schedule sched type lt countable for while do loop gt wh
313. ent that contains the word if followed by an expression in parentheses the condition a statement the action and an optional else clause the alternative action Appendix O Glossary 493 include file A text file that contains declarations used by a group of functions programs or users Also known as a header file include directive A preprocessor directive that causes the preprocessor to replace the statement with the contents of a specified file initialize To set the starting value of a data object initializer An expression used to initialize data objects inline function A function declared and defined simultaneously in a class definition You can also explicitly declare a function inline by using the keyword inline which is a hint to the compiler to perform inline expansion of the body of a function member Both member and nonmember functions can be inlined instruction A program statement that specifies an operation to be performed by the computer along with the values or locations of operands This statement represents the programmer s request to the processor to perform a specific operation integer A positive or negative whole number or zero integer constant A decimal octal or hexadecimal constant integral object A character object an object having variations of the type int or an object that is a bit field internal data definition A description of a variable appearing in a block that directs the syst
314. eparating the parameters is optional When you use the start parameter to start skipping heap checks you are trading off heap checks that are done implicitly against program execution speed You should therefore start with a small increment like 5 and slowly increase until the application is usable For example if you specify set HD SKIP 10 then every tenth debug memory function call performs a heap check If you specify set HD SKIP 5 100 then after 100 debug memory function calls only every fifth call performs a heap check Other than the heap check the debug functions behave exactly the same as usual Using Stack Traces Stack contents are traced for each allocated memory object If the contents of an object s stack change the traced contents are dumped The trace size is controlled by the HD STACK environment variable If this variable is not set the compiler assumes a stack size of 10 To disable stack tracing set the HD STACK environment variable to 0 196 C for AIX User s Guide Related Reading Writing Optimized Program Source Code This page contains tips for writing code to take advantage of the optimization features of the compiler The following language elements are discussed You can also refer to the Optimization Guide for Fortran C and C for more information about optimizing and tuning your code Related Reading Variables Use local variables preferably automatic variables as much as
315. eplaces the obsolete qrrm option Use qfloat rrm in your new applications Appendix A Compiler Options 263 qfloat rsqrt Specifies whether a sequence of code that involves division by the result of a square root qfloat norsqrt can be replaced by calculating the reciprocal of the square root and multiplying Allowing this replacement produces code that runs faster For O2 the default is qfloat norsqrt For O3 the default is qfloat rsqrt Use qfloat norsaqrt to override this default qstrict sets qfloat norsart qnostrict sets qfloat rsqrt Note that qfloat rsqrt means that errno will not be set for any sqrt function calls qfloat rsqrt has no effect when qarch pwr2 is also specified qfloat rsqrt has no effect unless qignerrno is also specified Changing the optimization level will not change the setting of the rsqrt option if rsqrt has already been specified If qfloat options are explicitly set the qstrict qnostrict option will not override those settings Otherwise the default setting appearing last is used qfloat spnans Generates extra instructions to detect signalling NaN on conversion from single precision to qfloat nospnans double precision The option nospnans specifies that this conversion need not be detected The hsflt option overrides the spnans option The qfloat nans option replaces the obsolete qfloat spnans and qspnans options Use qfloat nans in your new applications Example
316. eprocessor to generate a severe S compile time diagnostic error message Preprocessing continues but no object code is generated br err chascter pa Use the error directive as a safety check during compilation For example if your program uses preprocessor conditional compilation directives put error directives in the source file to prevent code generation if a section of the program is reached that should be bypassed For example the directive error Error in TESTPGM1 This section should not be compiled generates the following error message Error in TESTPGM1 This section should not be compiled Related Reading ifdef Preprocessor Directive The ifdef directive checks for the existence of macro definitions pee if cet feentiier E setement yea If the identifier specified is defined as a macro the tokens that immediately follow the condition are passed on to the compiler The following example defines MAX_LEN to be 75 if EXTENDED is defined for the preprocessor Otherwise MAX_LEN is defined to be 50 ifdef EXTENDED define MAX LEN 75 else define MAX LEN 50 endif 354 C for AIX User s Guide Related Reading indef Preprocessor Directive The ifndef directive checks for the existence of macro definitions Pe fncei center F emeni pa If the identifier specified is not defined as a macro the tokens that immediately follow the condition are passed on to the compiler A
317. er it is not part of the constant it is interpreted as a unary operator The limits for floating point values are set in the usr include float h include file Header files are described in the AIX Version 4 Files Reference The following are examples of floating point constants Floating Point Constant Value 5 3876e4 53876 4e 11 0 00000000004 le 5 100000 7 321E 3 0 007321 3 2E 4 32000 0 5e 6 0 0000005 0 45 0 45 6 e10 60000000000 Character Constants A character constant contains a sequence of characters or escape sequences enclosed in single quotation mark symbols gt ET obaracter Scape se cuence At least one character or escape sequence must appear in the character constant The characters can be any from the source program character set excluding the single quotation mark backslash and new line symbols The prefix L indicates a wide character constant A character constant must appear on a single logical source line The value of a character constant containing a single character is the numeric representation of the character in the character set used at run time The value of a wide character constant containing a single multibyte character is the code for that character as defined by the mbtowc function A character constant has type int A wide character constant is represented by a double byte character of type wchar_t an integral type defined in the lt stddef h gt include file Header files a
318. er appears within the literal a second character is inserted before the original when the macro is expanded Appendix D Preprocessor Directives and Related Information 377 e lf the argument passed to the macro contains a double quotation mark character a character is inserted before the when the macro is expanded e lf the argument passed to the macro contains a single quotation mark character a character is inserted before the when the macro is expanded e The conversion of an argument into a string literal occurs before macro expansion on that argument e f more than one operator or operator appears in the replacement list of a macro definition the order of evaluation of the operators is not defined e lf the result of the macro expansion is not a valid character string literal the behavior is undefined The following example demonstrates the use of the operator Sample Preprocessor Macro Definitions define STR x x define XSTR x STR x define ONE 1 Invocation Result of Macro Expansion STR n yy n n n n E XSTR hello MW helio Related Reading Preprocessor Macro Operator Use the operator according to the following rules The operator cannot be the very first or very last item in the replacement list of a macro definition e The last token of the item in front of the operator is concatenated with first token of the item fo
319. er expanding the code to a straight sequence of statements For example array 0 b k 1 c m 1 array 1 b k 2 c m 2 array 2 b k 3 c m 3 array 3 b k 4 c m 4 array 4 b k 5 c m 5 would run faster than for i 0 i lt 5 i array i b k i c m i The compiler will perform automatic unrolling of inner loops when the O3 option is specified In this case the compiler will unroll the loop once 200 C forAIX User s Guide Related Reading Conversions Avoid forcing the compiler to convert numbers between integer and floating point internal representations Conversions require several instructions including some double precision floating point arithmetic For example float array 10 float x 1 0 int i for i 0 i lt 9 i No conversions needed array i array i x x x 1 0 for i 0 i lt 9 i Multiple conversions needed array i array i i When you must use mixed mode arithmetic code the fixed point and floating point arithmetic in separate computations wherever possible Related Reading Arithmetic Constructions Wherever possible use multiplication rather than division For example xe 1 0 3 0 produces faster code than x 3 0 Assigning the reciprocal of the divisor to a temporary variable and then multiplying by that variable is beneficial especially if you divide many values by the same number in your code This is atte
320. er name as in a define preprocessor directive qopt dataimported Mark data as local or imported fro fre fro fro fro fre fro fro O O O O O O O O gt gt 5 gt 5 5 5 5 h h Appendix A Compiler Options 219 Specifies that all typedef declarations struct union and enum type definitions are included for debugger processing n _ _ i i n ia o we Milttrap on page 264 noflttrap l 220 C for AIX User s Guide Allows use of digraph character sequences in your program Allows the symbol to be used in the names of identifiers Generates symbols that tools based on the Dynamic Probe Class Library DPCL can use to see the structure of an executable file Runs the source files named in the compiler invocation through the preprocessor Specifies the amount of storage occupied by the enumerations Generates bind time type checking information and checks for compile time consistency Names an alternative configuration file for xlc Linkage editor Id command option only Passes to the linkage editor the filename of a file containing a list of input files to be processed Collect program information for use with the AIX fdpr performance tuning utility Specifies the minimum severity level of diagnostic messages to be reported Specifies various floating point options to speed up or improve the accuracy of floating point operations Ge
321. ere exp represents a scalar expression and sched type represents any scheduling algorithm as valid for the schedule directive When the if argument is specified the loop executes in parallel only if exp evaluates to TRUE at run time Otherwise the loop executes sequentially The loop will also run sequentially if it is in a critical section Notes This pragma can be applied to a wide variety of C loops and the compiler will try to determine if a loop is countable or not Program sections using the ibm parallel_loop pragma must be able to produce a correct result in both sequential and parallel mode For example loop iterations must be independent before the loop can be parallelized Explicit parallel programming techniques involving condition synchronization are not permitted This pragma can be combined with the ibm schedule pragma to select a specific parallel process scheduling algorithm For more information see the description for the ibm schedule pragma A warning is generated if this pragma is not followed by a countable loop Example pragma ibm parallel loop The loop will execute in parallel if N is greater or equal to 10000 Dynamic scheduling will be used pragma ibm parallel loop if N gt 10000 schedule dynamic for i 0 i lt N i ali z Related Reading pragma ibm permutation Preprocessor Directive The permutation pragma asserts that specified arrays in the chosen loop contain no repeated values
322. erformed by the compiler Pragmas fall into two general categories 1 The first category of pragmas lets you give the compiler information on the characteristics of a specific countable loop The compiler uses this information to perform more efficient automatic parallelization of the loop 2 The second category gives you explicit control over parallelization Use these pragmas to force or suppress parallelization of a loop apply specific parallelization algorithms to a loop and synchronize access to shared variables using critical sections OpenMP Directives OpenMP directives exploit shared memory parallelism by defining various types of parallel regions Parallel regions can include both iterative and non iterative segments of program code Pragmas fall into four general categories Copyright IBM Corp 1995 1999 37 1 The first category of pragmas lets you define parallel regions in which work is done by threads in parallel Most of the OpenMP directives either statically or dynamically bind to an enclosing parallel region 2 The second category lets you define how work will be distributed across the threads in a parallel region 3 The third category lets you control synchronization among threads 4 The fourth category lets you define the scope of data visibility across threads Related Reading Countable Loops A loop is considered to be countable if e there is no branching into or outside of the loop e the incr
323. eristics Using this option when compiling other application programs can produce incorrect results without warning See A before you use the qrndsngl option Related Reading ro Option Type Default Value pragma options Syntax qro qnoro RO NORO Purpose Specifies the storage type for string literals Default The default with xle and c89 is ro The default with cc is noro Notes If ro is specified the compiler places string literals in read only storage If noro is specified string literals are placed in read write storage You can also specify the storage type in your source program using pragma strings storage_ type where storage_type is read only or writable Placing string literals in read only memory can improve runtime performance and save storage but code that attempts to modify a read only string literal generates a memory error Example To compile myprogram c so that the storage type is writable enter xlc myprogram c qnoro Related Reading roconst Option Type Default Value pragma options Syntax Appendix A Compiler Options 317 qroconst qnoroconst ROCONST NOROCONST Purpose Specifies the storage location for constant values Default The default with xle and c89 is roconst The default with cc is noroconst Notes If qroconst is specified the compiler places constants in read only storage If qnoroconst is specified constant values are placed in read write stor
324. ers of the function Mactan decks retor m _ extern toe _specner static p l p param eter A function is declared implicitly by its appearance in an expression if it has not been defined or declared previously the implicit declaration is equivalent to a declaration of extern int func_name The default return type of a function is age amp To indicate that the function does not return a value declare it with a return type of A function cannot be declared as returning a data object having a Data Type Qualifie page B pe G on page 115 type but it can return a pointer to a volatile or const object Also a function cannot return a value that has a type of array or function If the called function returns a value that has a type other than age declare the function before the function call Even if a called function returns a type int explicitly declaring the function prior to its call is good programming practice Some declarations do not have parameter lists the declarations simply specify the types of parameters and the return values such as in the following example int func int long Related Reading 138 C for AIX User s Guide Examples of Function Declarations The following example defines the function absolute with the return type double Because this is a non integer return type absolute is declared prior to the function call include lt stdio h gt double absolute double int mai
325. es and statement labels are in four different name spaces no conflict occurs among the four items named student in the following example int get_item struct student structure tag x char student 20 structure member x int section int id student structure variable goto student student null statement label return 0 Each occurrence of student is interpreted by its context in the program For example when student appears after the keyword struct it is a structure tag When student appears after either of the member selection operators or gt the name refers to the structure member When student appears after the goto statement control is passed to the null statement label In other contexts the identifier student refers to the structure variable Related Reading Preprocessor Directives Preprocessing is a step that takes place before compilation that lets you e Replace tokens in the current file with specified replacement tokens e Imbed files within the current file e Conditionally compile sections of the current file e Generate diagnostic messages e Change the line number of the next line of source and change the file name of the current file A token is a series of characters delimited by white space The only white space allowed on a preprocessor directive is the space horizontal tab vertical tab form feed and comments The new line character can also separate preproce
326. es lf used pragma ALIAS suboption must appear before the first program statement The compiler will apply aliasing assertions according to the following suboptions NO TYPeptr Pointers to different types are never aliased In other words in the compilation unit no two pointers of different types will point to the same storage location NO ALLPtrs Pointers are never aliased this also implies qalias typeptr Therefore in the compilation unit no two pointers will point to the same storage location NO ADDRtaken Variables are disjoint from pointers unless their address is taken Any class of variable for which an address has not been recorded in the compilation unit will be considered disjoint from indirect access through pointers NO ANSI Type based aliasing is used during optimization which restricts the lvalues that can be safely used to access a data object The optimizer assumes that pointers can only point to an object of the same type This ansi is the default for the xic and c89 compilers This option has no effect unless you also specify the O option If you select noansi the optimizer makes worst case aliasing assumptions It assumes that a pointer of a given type can point to an external object or any object whose address is already taken regardless of type This is the default for the cc compiler The following are not subject to type based aliasing e Signed and unsigned types For example a pointer to a signed in
327. es memory from it then uses _debug_heapmin to release the memory Note You must compile this example with the qheapdebug option to map the _uheapmin calls to _debug_uheapmin include lt stdlib h gt include lt stdio h gt include lt string h gt include lt umalloc h gt int main void Heap t myheap char ptr Use default heap as user heap myheap _udefault NULL Allocate a large object if NULL ptr char umalloc myheap 60000 puts Cannot allocate memory from user heap n exit EXIT_FAILURE memset ptr x 60000 free ptr debug uheapmin will attempt to return the freed object to the system if 0 _uheapmin myheap puts debug uheapmin returns failed n exit EXIT_FAILURE return 0 Related Reading _debug_umalloc Reserve Memory Blocks from User Heap Format Appendix F C for AIX Debug Functions 431 include lt umalloc h gt void debug _umalloc Heap t heap size_t size const char file size t line Language Level Extension _debug_umalloc is the debug version of _umalloc Like _umalloc it reserves storage space from the heap you specify for a block of size bytes _debug_umalloc also sets all the memory it allocates to OxAA so you can easily locate instances where your program uses the data in the memory without initializing it first In addition debug umalloc makes an implicit call to _uheap_check and stores the name
328. estroy the heap call udestroy If blocks of memory are still allocated somewhere you can force the destruction Destroying a heap removes it entirely even if it was shared by other processes Again performing operations on a heap after you ve destroyed it causes undefined behavior After you destroy your fixed size heap it is up to you to return the memory for the heap the initial block of memory you supplied to ucreate and any other blocks added by _uaddmem to the system Related Reading Creating and Using an Expandable Heap When using a fixed size heap the initial block of memory must be large enough to satisfy all allocation requests made to it You can also however create a heap that can expand and contract as your program needs demand With the C for AIX runtime heap when not enough storage is available for your malloc request the runtime gets additional storage from the system Similarly when you minimize the heap with _heapmin or when your program ends the runtime returns the memory to the operating system When you create an expandable heap you provide your own functions to do this work we ll call them getmore fn and release fn although you can name them whatever you choose You specify pointers to these functions as the last two parameters to ucreate instead of the NULL pointers you used to create a fixed size heap For example Heap_t growHeap static char block _HEAP MIN SIZE get block growHeap _ucre
329. et Consistency of return statements trd Possible truncation or loss of data or precision tru Variable names truncated by the compiler uni Unitialized variables use Unused auto and static variables vft Generation of virtual function tables Related Reading pragma isolated_call Preprocessor Directive The pragma isolated_call directive lists functions that do not alter data objects visible at the time of the function call Appendix D Preprocessor Directives and Related Information 371 ee t pregma Iackted_eall A ee 1 4 The pragma must appear before calls to the functions in the identifier list The identifiers listed must be declared before they are used in the pragma and must be of type function or a typedef of function The pragma informs the compiler that none of the functions listed has side effects Functions are cosidered to have side effects if they e Access a volatile object e Modify an external object e Modify a file e Call a function that does any of the above Any change in the state of the runtime environment is considered a side effect Passing function arguments by reference is one side effect that is allowed but in general functions with side effects can give incorrect results when listed in pragma isolated_call directives Marking a function as isolated indicates to the optimizer that external and static variables cannot be changed by the called function and that references to storage can b
330. ext example declares pvish as a pointer to a function that takes no parameters and returns a char object char pvish void Assigning Pointers When you use pointers in an assignment operation you must ensure that the types of the pointers in the operation are compatible The following example shows compatible declarations for the assignment operation float subtotal float sub ptr sub ptr amp subtotal printf The subtotal is f n sub ptr 90 C for AIX User s Guide The next example shows incompatible declarations for the assignment operation double league int minor minor amp league error Initializing Pointers The initializer is an equal sign followed by the expression that represents the address that the pointer is to contain The following example defines the variables time and speed as having type double and amount as having type pointer to a double The pointer amount is initialized to point to total double total speed amount amp total The compiler converts an unsubscripted array name to a pointer to the first element in the array You can assign the address of the first element of an array to a pointer by specifying the name of the array The following two sets of definitions are equivalent Both define the pointer student and initialize student to the address of the first element in section int section 80 int student section is equivalent to int section 80 in
331. f ACUs for a function the functions that are inlined are not always the best candidates for inlining As much as possible use the _Inline or inline keyword to choose the functions to be inlined When you use inlining you need more stack space When a function is called its local storage is allocated at the time of the call and freed when it returns to the calling function If that same function is inlined its storage is allocated when the function that calls it is entered and is not freed until that calling function ends Ensure that you have enough stack space for the local storage of the inlined functions in order to avoid a stack overflow Restrictions on Inlining The following restrictions apply to inlining If the definition and reference to a given function reside in different files all such files must be compiled and linked using the qipa compiler option To inline across source files you must place the function definition qualified with _Inline in a header file that is included by all source files where the function is to be inlined Turn off inlining if you plan to debug your executable module Inlining can make debugging difficult For example if you set an entry breakpoint for a function call but the function is inlined the breakpoint will not work The Performance Analyzer treats an inlined function as part of the function in which it is inlined A function is not inlined during an inline expansion of itself For a funct
332. f Usage The following line defines the macro SUM as having two parameters a and b and the replacement tokens a b define SUM a b a b This definition causes the preprocessor to change the following statements if the statements appear after the previous definition c SUM x y c d SUM x y In the output of the preprocessor these statements would appear as c x y c d x y Use parentheses to ensure correct evaluation of replacement text For example the definition define SQR c c c requires parentheses around each parameter c in the definition in order to correctly evaluate an expression like y SQR a b The preprocessor expands this statement to y a b a b Without parentheses in the definition the correct order of evaluation is not preserved and the preprocessor output iS y atb a tb Notes 1 2 Arguments of the and operators are converted before replacement of parameters in a function like macro The number of arguments in a mcro invocation must be the same as the number of parameters in the corresponding macro definition Commas in the macro invocation argument list do not act as argument separators when they are e in character constants e in string literals e surrounded by parenthesis The scope of a macro definition begins at the definition and does not end until a corresponding undef directive is encountered If there is no corres
333. f processors available on the system usrthds num num represents the number of user threads expected This option should be used if the program code explicitly creates threads in which case num should be set to the number of threads created The default value for num is 0 402 C for AIX Users Guide stack num num specifies the largest amount of space required for a thread s stack The default value for num is 32768 Performance Tuning Options Spins num yields num delays num num represents the number of loop spins before a yield occurs When a thread completes its work the thread continues executing in a tight loop looking for new work One complete scan of the work queue is done during each busy wait state An extended busy wait state can make a particular application highly responsive but can also harm the overall responsiveness of the system unless the thread is given instructions to periodically scan for and yield to requests from other applications A complete busy wait state for benchmarking purposes can be forced by setting both spins and yields to 0 The default value for num is 100 num represents the number of yields before a sleep occurs When a thread sleeps it completely suspends execution until another thread signals that there is work to do This provides better system utilization but also adds extra system overhead for the application The default value for num is 100 num represents a period of d
334. f the array provided the array has been previously declared An unsubscripted array name with square brackets for example region is allowed only when declaring arrays at file scope or in the argument list of a function declaration In declarations only the first dimension can be left empty and you must specify the sizes of any additional dimensions declared Whenever an array is used in a context Such as a parameter where it cannot be used as an array the identifier is treated as a pointer The only exceptions are when an array is used as an operand to the sizeof expression or with an address amp operator Initializing Arrays The initializer for an array contains the symbol followed by a comma separated list of constant expressions enclosed in braces You do not need to initialize all elements in an array Elements that are not initialized in extern and static definitions only receive the value O of the appropriate type You cannot have more initializers than the number of elements in the array The initializer must be a constant expression if the structure has static storage duration or if you are compiling your source code in ansi mode Note Array initializations can be either fully braced with braces around each dimension or unbraced with only one set of braces enclosing the entire set of initializers Avoid placing braces around some dimensions and not around others Initializing a one dimensional character array
335. f the heap is consistent or not they do not provide the details that the debug memory management functions do What you may choose to do is add calls to heap checking functions in places you suspect possible memory problems If the heap turns out to be corrupted at that point you may want to rebuild with the qheapdebug option Note When the debug memory option qheapdebug is specified code is generated to pre initialize the local variables for all functions This makes it much more likely that uninitialized local variables will be found during the normal debug cycle rather than much later usually when the code is optimized 184 C for AIX Users Guide Regardless of which debugging functions you choose your program requires additional memory to maintain internal information for these functions If you are using fixed size heaps you may have to increase the heap size in order to use the debugging functions Related Reading Changing the Default Heap Used in a Program The regular memory management functions malloc and so on always use whatever heap is currently the default for that thread The initial default heap for all C for AIX applications is the runtime heap provided by C for AIX However you can make your own heap the default by calling udefault Then all calls to the regular memory management functions allocate from your heap instead of the runtime heap The default heap changes only for the thread where you call udefault
336. fied with an ellipsis as in function the compiler widens all floating point arguments to double precision Integral arguments except for long int are widened to int Because of this widening some data types cannot be passed between Pascal and C without explicit conversions and Pascal routines cannot have value parameters of certain data types The following information refers to call by value as in C In the following list arguments are classified as floating values or nonfloating values e Each nonfloating scalar argument requires 1 word and appears in that word exactly as it would appear in a GPR It is right justified if language semantics specify and is word aligned e Each float value occupies 1 word float doubles occupy 2 successive words in the list and long doubles occupy either 2 or 4 words depending on the setting of the the qldbl128 qlongdouble option e Structure values appear in successive words as they would anywhere in storage satisfying all appropriate alignment requirements Structures are aligned to a fullword and occupy sizeof struct X 3 4 fullwords with any padding at the end A structure smaller than a word is left justified within its word or register Larger structures can occupy multiple registers and can be passed partly in storage and partly in registers e Other aggregate values are passed val by ref that is the compiler actually passes their addresses and arranges for a copy to be made in the i
337. fies what aggregate alignment rules the compiler uses for file compilation qopt ansialias Specifies whether type based aliasing is to be used during optimization 218 C for AIX User s Guide arch com Specifies the architecture on which the executable program will be run noassert Requests the compiler to apply aliasing assertions to your compilation unit noattr Produces a compiler listing that includes an attribute listing for all identifiers flag Determines substitute path names for the compiler assembler linkage editor and preprocessor bitfields on page 240 flag unsigned Specifies if bitfields are signed ortl on page 240 flag Tells the linkage editor to accept both so and a library file types flag bdynamic Determines which types of library files are searched by the linkage editor flag Preserves comments in preprocessed output flag Instructs the compiler to pass source files to the compiler only Specifies the cache configuration for a specific execution machine chars unsigned Instructs the compiler to treat all variables of type char as either signed or unsigned nocheck Generates code which performs certain types of run time checking nocompact When used with optimization reduces code size where possible at the expense of execution speed nocpluscmt Use this option if you want C comments to be recognized in C source files flag Defines the identifi
338. file name information for the debugger Notes This option produces minimal debugging information so the resulting object size is smaller than that produced if the g debugging option is specified You can use the debugger to step through the source code but you will not be able to see or query variable information The traceback table if generated will include line numbers Avoid using this option with O optimization option The information produced may be incomplete or misleading If you specify the qlinedebug option the inlining option defaults to Q no functions are inlined The g option overrides the qlinedebug option If you specify g qnolinedebug on the command line qnolinedebug is ignored and the following warning is issued 1506 W Option qnolinedebug is incompatible with option g and is ignored Example To compile myprogram c to produce an executable programtesting so you can step through it with a debugger enter xlc myprogram c o testing qlinedebug Related Reading list Option Type Default Value pragma options Syntax qlist qnolist LIST NOLIST Appendix A Compiler Options 291 Purpose Produces a compiler listing that includes an object listing Notes Options that are not defaults appear in all listings even if nolist is specified The noprint option overrides this option Example To compile myprogram c to produce an object listing enter xlc myprogram c qlist Re
339. filel o file2 0 file3 0 file4 o Related Reading pg Option Type Default Value pragma options 7 Syntax pg Purpose Sets up the object files for profiling but provides more information than is provided by the p option If the qtbtable option is not set the pg option will generate full traceback tables Example To compile myprogram c for use with the AIX gprof command enter Appendix A Compiler Options 311 xlc myprogram c pg Remember to compile and link with the pg option For example xlc myprogram c pg c xlc myprogram o pg 0 program Related Reading o On page gprof command in the AIX Version 4 Commands Reference for details on profiling phsinfo Option Type Default Value pragma options e a Syntax qphsinfo qnophsinfo Purpose Reports the time taken in each compilation phase Phase information is sent to standard output Example To compile myprogram c and report the time taken for each phase of the compilation enter xlc myprogram c qphsinfo Related Reading proclocal procimported procunknown Option Type Default Value pragma options qoption proclocal PROCLOCal PROCIMPorted PROCUNKnown Syntax qproclocal qproclocal names qprocimported qprocimported names qprocunknown qprocunknown names PROCLOCAL PROCLOCAL names PROCIMPORTED PROCIMPORTED names PROCUNKNOWN PROCUNKNOWN names Purpose Marks functions as local imported or unknown
340. files named in the compiler invocation and creates an output preprocessed source file for each input source file flag Sets up the object files produced by the compiler for profiling nopascal Ignores the word pascal in type specifiers and function declarations fre fro fre fro fro fro fro fro fro O O O O O O O O O gt 5 gt 5 5 5 gt gt 5 h h h Appendix A Compiler Options 223 Kodf1 pdf on page 309 qopt nopdft Tunes optimizations through nopdf2 Profile Directed Feedback flag Sets up the object files for profiling but provides more information than is provided by the p option Fphsinfo on page 314 Oo on page qopt nophsinfo Reports the time taken in each compilation phase proclocal Mark functions as local imported or unknown Q Fproto on page 313 o on page qopt noproto Assumes all functions are prototyped flag See FQ on page 314 Attempts to inline functions instead of generating calls to a function 8 Fr on page 314 page flag Produces a relocatable object qopt norndsng Specifies that the result of each single precision float operation is to be rounded to single precision Q Ero on page 317 page qopt Specifies the storage type for string literals roconst on page 317 qopt roconst Specifies the storage location for constant values norrm Prevents floating point optimizations that are incompatible with run time rounding to
341. fltint which checks floating point to integer conversions for out of range values This suboption must only be used with an optimization option e For O2 the default is qfloat nofltint e For O3 the default is qfloat fltint To include range checking in floating point to integer conversions with the O3 option specify qfloat nofltint e qstrict sets qfloat nofltint e qnostrict sets qfloat fltint Changing the optimization level will not change the setting of the fltint option if fltint has already been specified If qfloat options are explicitly set the qstrict qnostrict option will not override those settings Otherwise the default setting appearing last is used qfloat fold Specifies that constant floating point expressions are to be evaluated at compile time rather qfloat nofold than at run time The qfloat fold option replaces the obsolete qfold option Use qfloat fold in your new applications 262 C for AIX User s Guide qfloat hsflt qfloat nohsflt qfloat hssng1 qfloat nohssngl qfloat maf qfloat nomaf qfloat nans qfloat nonans qfloat rndsngl qfloat norndsng qfloat rrm qfloat norrm Speeds up calculations by enforcing the rounding of computed values to single precision before storing and on conversions from floating point to integer nohsflt specifies that single precision expressions are rounded after expression evaluation and that floating point to inte
342. for optimization Pay special attention to the compiler options used to compile the files because you will need to use the same options later 2 Run the program all the way through using a typical data set The program records profiling information when it finishes You can run the program multiple times with different data sets and the profiling information is accumulated to provide an accurate count of how often branches are taken and blocks of code are executed Important Use data that is representative of the data that will be used during a normal run of your finished program 3 Recompile your program using the same compiler options as before but changing qpdf1 to qpdf2 Remember that L l and some others are linker options and you can change them at this point In particular leave the lpdf option out In this second compilation the accumulated profiling information is used to fine tune the optimizations The resulting program contains no profiling overhead and runs at full speed For optimum performance use the O3 option with all compilations when you use PDF as in the example above With O2 optimization one of the most important PDF optimizations moving code before branches to fill delay slots is not done The profile is placed in the current working directory or the directory named by the PDFDIR environment variable if that variable is set To avoid wasting compilation and execution time make sure the PDFDIR en
343. for the inlining phase of the compiler Path name to be used to link C programs The default is bin Id List of options that are directed to the linkage editor part of the compiler These override all normal processing by the compiler and are directed to the linkage editor If the corresponding flag takes a parameter the string is formatted for the Aix getopt subroutine as a concatenation of flag letters with a letter followed by a colon Library options separated by commas that the compiler passes as the last parameters to the linkage editor libraries2 specifies the libraries that the linkage editor is to use at link edit time for both profiling and nonprofiling The default is empty Path name of the object file passed as the first parameter to the linkage editor if you have specified the p option The default is lib mcrt0 o A string of option flags separated by commas to be processed by the compiler as if they had been entered on the command line The suffix for object files The default is o Library options separated by commas that the compiler passes to the linkage editor when profiling options are specified proflibs specifies the profiling libraries used by the linkage editor at link edit time The default is L lib profiled and L usr lib profiled The suffix for assembler files The default is s Values for attributes are taken from the named stanza and from the local stanza For single valued attributes values in the
344. fore optimizing it with the fdpr performance tuning utility Optmization data is stored in the object file For more information on using the fdpr performance tuning utilty refer to the AIX Version 4 Commands Reference or enter the command man fdpr Example To compile myprogram c so it include data required by the fdpr utility enter xlc myprogram c qfdpr Related Reading 260 C for AIX User s Guide flag Option Type Default Value pragma options Syntax qflag severityl severity2 FLAG severityl severity2 Purpose Specifies the minimum severity level of diagnostic messages to be reported in a listing and displayed on a terminal Notes severityl Message level reported in listing severity2 Message level reported on terminal You must specify a level for both severity and severity2 Diagnostic messages have the following severity levels Informational Warning Error Severe Error Unrecoverable Error cn oOo Specifying informational messages does not turn on the qinfo option Example To compile myprogram c so that the listing shows all messages that were generated and your workstation displays only error and higher messages enter xlc myprogram c qflag I E Related Reading Option Type Default Values pragma options qoption noemulate FLOAT nofltint fold nohsflt nohssngl maf norndsngl norrm norsqrt nospnans Syntax Appendix A Compiler Options 261 qfloat suboptions FLOAT subo
345. function call is an lvalue only if the function returns a reference A function can call itself If you want a function to change the value of a variable pass a pointer to the variable you want changed When a pointer is passed as a parameter the pointer and not the object pointed to is copied Argument that are arrays and functions are converted to pointers before being passed as function arguments Arguments passed to non prototyped C functions undergo conversions Type short or char parameters are converted to int and float parameters are converted to double Use a cast expression for other conversions 72 C for AIX User s Guide The compiler compares the data types provided by the calling function with the data types that the called function expects The compiler might also perform type conversions if the declaration of the function is e in function prototype format and the parameters differ from the prototype or e visible at the point where the function is called Related Reading Examples of Function Calls For example the declaration of funct is a protoype When function funct is called the parameter f is converted to a double and parameter c is converted to an int char funct double d int i main float f char c funct f c f is a double c is an int The order in which parameters are evaluated is not specified Avoid calls such as method samplel batch process batch process In this ex
346. g compiler option This option maps all calloc calls to _debug_calloc Note The qheapdebug option maps all calls to memory management functions including heap specific versions to their debug counterparts To prevent a call from being mapped parenthesize the function name To reallocate or free memory allocated by debug _calloc use debug _realloc and debug _ free you can also use realloc and free if you do not want debug information about the operation A heap specific version _debug_ucalloc is available debug_calloc always allocates memory from the default heap Return Value _debug_calloc returns a pointer to the reserved space If not enough memory is available or if num or size is 0 debug _calloc returns NULL Example This example reserves storage of 100 bytes It then attempts to write to storage that was not allocated When _debug_calloc is called again heap check detects the error generates several messages and stops the program Note You must compile this example with the qheapdebug option to map the calloc calls to _debug_calloc include lt stdlib h gt include lt stdio h gt include lt string h gt int main void char ptrl ptr2 if NULL ptrl char calloc 1 100 puts Could not allocate memory block exit EXIT FAILURE memset ptr1 a 105 overwrites storage that was not allocated ptr2 char calloc 2 20 this call to calloc invokes _heap check puts debug _c
347. ge general purpose floating point and special purpose registers e Stack e The calling routine s responsibilities e The called routine s responsibilities Related Reading Sample Program C Calling Fortran A C program can call a Fortran function or subroutine The following example illustrates how program units written in different languages can be combined to create a single program It also demonstrates parameter passing between C and Fortran subroutines with different data types as arguments include lt iostream h gt extern double add int double int double double arl1 4 1 0 2 0 3 0 4 double ar2 4 5 0 6 0 7 0 8 main int Xs y double Z x 3 0 0 214 C for AIX User s Guide z add amp x arl y ar2 Call Fortran add routine Note Fortran indexes arrays 1 n C indexes arrays 0 n 1 printf The sum of 1 0f and 1 0f is 2 0f n arl x 1 ar2 y 1 z The Fortran subroutine is C Fortran function add f for C interlanguage call example C Compile separately then link to C program REAL FUNCTION ADD 8 A B C D REAL 8 B D INTEGER 4 A C DIMENSION B 4 D 4 ADD B A D C RETURN END Related Reading Chapter 8 Using C for AIX with Other Programming Languages 215 216 C for AIX User s Guide Appendix A Compiler Options The compiler options pages describe each of the compiler options including e The
348. ge units in column major order array elements in the same column occupy adjacent memory locations The following example shows how a two dimensional array declared by A 38 2 in C A 1 3 1 2 in Pascal and by A 8 2 in Fortran is 208 C for AIX User s Guide stored Storage of a Two Dimensional Array Storage Unit C and C Element Name Pascal Element Name Fortran Element Name Aol ati Att e In general for a multidimensional array if you list the elements of the array in the order they are laid out in memory a row major array will be such that the rightmost index varies fastest while a column major array will be such that the leftmost index varies fastest Related Reading Using the Subroutine Linkage Conventions in Interlanguage Calls The subroutine linkage conventions describes the machine state at subroutine entry and exit Routines that are compiled separately in the same or different languages are linked when the programs are linked and run when called The AlX Version 4 Assembler Language Referencedescribes the Subroutine Linkage Convention in detail The RISC System 6000 linkage convention provides fast and efficient subroutine linkage between languages It specifies how parameters are passed taking full advantage of the large number of floating point registers FPRs and general purpose registers GPRs and minimizes the saving and restoring of registers on subroutine entry and exit Chapter 8 Using C for A
349. ger conversions are to be checked for out of range values The hsflt option overrides the rndsngl nans and spnans options Note The hsflt option is for specific applications in which floating point computations have known characteristics Using this option when you are compiling other application programs can produce incorrect results without warning The qfloat hsflt option replaces the obsolete qhsflt option Use qfloat hsflt in your new applications Specifies that single precision expressions are rounded only when the results are stored into float memory locations nohssngl specifies that single precision expressions are rounded after expression evaluation Using hssngl can improve runtime performance but is safer than using qfloat hsflt The qfloat hssngl option replaces the obsolete qhssngl option Use qfloat hssngl in your new applications Makes floating point calculations faster and more accurate by using floating point multiply add instructions where appropriate The results may not be exactly equivalent to those from similar calculations performed at compile time or on other types of computers This option may affect the precision of floating point intermediate results The qfloat maf option replaces the obsolete qmaf option Use qfloat maf in your new applications Generates extra instructions to detect signalling NaN Not a Number when converting from single precision to double precision at run time The option no
350. gger an exception e Relaxing conformance to IEEE rules e Reassociating floating point expressions Unless explicitly set otherwise by the qfloat option e qstrict sets qfloat nofltint norsaqrt e qnostrict sets qfloat fltint rsqrt You can use qfloat fltint and qfloat rsqrt to override the qstrict settings For example e Using O3 qstrict qfloat fltint means that qfloat fltint is in effect but there are no other aggressive optimizations e Using O3 qnostrict qfloat norsqrt means that the compiler performs all aggressive optimizations except qfloat rsart Defaults Default setting for the strict option varies according to Ooptimization level in effect Optimization Default setting for level strict option qstrict qstrict qnostrict qnostrict WD O You can override the default settings by explicitly setting either qstrict or qnostrict In the example below qstrict is active regardless of the O3 optimization level selected xlc myprogram c 03 qstrict qfloat fltint rsaqrt Example To compile myprogram c so that the aggressive optimizations of O3 are turned off range checking is turned off qfloat fltint and division by the result of a square root is replaced by multiplying by the reciprocal qfloat rsqrt enter xlc myprogram c 03 qstrict qfloat fltint rsqrt 326 C for AIX User s Guide Related Reading strict_induction pion seww TS Sd o Syntax qstrict_inductio
351. ggregate definition but it can be used on an aggregate definition nested within another aggregate definition The __align specifier cannot be used in the following situations e Individual elements within an aggregate definition e Variables declared with incomplete type e Aggregates declared without definition e Individual elements within an aggregate definition e Individual elements of an array e Other types of declarations or definitions such as typedef function and enum e Where the size of variable alignment is smaller than the size of type alignment Examples Applying __ align to first level variables int _align 1024 varA varA is aligned on a 1024 byte boundary and padded with 1020 bytes x Static int align 512 varB varB is aligned on a 512 byte boundary and padded with 508 bytes int align 128 functionB An error x typedef int _align 128 T An error x __align enum C a b c An error x Applying __ align to align and pad aggregate tags without affecting aggregate members 442 C for AIX User s Guide __align 1024 struct structA int i int js struct structA is aligned on a 1024 byte boundary with size including padding of 1024 bytes __align 1024 union unionA int i int j union unionA is aligned on a 1024 byte boundary with size including padding of 1024 bytes Applying __ align to a structure or union where the size and alignment of the aggregate us
352. gma options align reset lt A unaffected by this pragma AA Macintosh alignment rules still in effect x Example 2 Affecting Only Aggregate Definition Using the compiler invocation xlc file2 c lt default alignment rule for file is RISC System 6000 since no alignment rule specified Where file2 c has extern struct A Al typedef struct A A2 pragma options align packed lt use packed alignment rules struct A int a char Cc i3 pragma options align reset lt Go back to default alignment rules struct A Al lt aligned using packed alignment rules since A2 A3 this rule applied when struct A was defined Example 3 Sample bit_packed Fields Assuming the following structure is declared pragma options align bit_packed Struct 4 int a 8 int 2 12 int d 2 4 int e 3 mt 0 int f 1 char g AS pragma options align reset The structure takes on the following characteristics sizeof A 7 and the layout of A is Member Name a Appendix A Compiler Options 235 Note that there is no padding between bitfield members c and d Related Reading ansialias Option Type Default Value pragma options Syntax qansialias qnoansialias ANSIALIAS NOANSIALIAS Purpose Specifies whether type based aliasing is to be used during optimization Type based aliasing restricts the lvalues that can be used to acces
353. gram c to produce an assembler language file myprogram s enter xlc myprogram c S To assemble this program to produce an object file myprogram o enter xlc myprogram s c To compile myprogram c to produce an assembler language file asmprogram s enter xlc myprogram c S o asmprogram s Appendix A Compiler Options 319 Related Reading AIX Version 4 Files Reference showinc Option Type Default Value pragma options Syntax qshowinc qnoshowinc SHOWINC Purpose If used with qsource all the include files are included in the source listing Example To compile myprogram c so that all included files appear in the source listing enter xlc myprogram c qsource qshowinc Related Reading smp Option Type Default Value pragma options P aopton mom Syntax qnosmp qsmp suboption suboption Purpose Specifies if and how parallelized object code is generated according to suboption s specified Suboption Description aut Enables or disables automatic parallelization noauto auto is the default if qsmp is specified without the omp suboption Otherwise the default is noauto explicit Enables or disables pragmas controlling explicit parallelization of countable loops noexplicit oo explicit is the default If noexplicit is in effect pragma ibm omp parallel_loop is not honored by the compiler 320 C for AIX User s Guide nested par nonested_ par omp noomp rec_locks n
354. groups of diagnostic messages on or off The pragma info directive overrides any info options stated on the command line Available options are all Turns on all diagnostic checking none Turns off all diagnostic suboptions for specific portions of your program restore Restores the options that were in effect before the previous pragma info directive Because pragma info operates like a stack the options restored may not be those given on the command line If no options were previously in effect pragma info restore does nothing 370 C for AIX User s Guide group Turns on specific groups of messages where group can be one or more of group Type of messages returned cmp Possible redundancies in unsigned comparisons cnd Possible redundancies or problems in conditional expressions cns Operations involving constants cnv Conversions dcl Consistency of declarations eff Statements with no effect enu Consistency of enum variables ext Unused external definitions gen General diagnostic messages gnr Generation of temporary variables got Use of goto statements ini Possible problems with initialization inl Functions not inlined Tan Language level effects obs Obsolete features ord Unspecified order of evaluation par Unused parameters por Nonportable language constructs ppc Possible problems with using the preprocessor ppt Trace of preprocessor actions pro Missing function prototypes rea Code that cannot be reached r
355. haracter sequence must be adjacent with nothing between them Everything to the right of them until the end of the logical source line as indicated by a new line character is treated as a comment The delimiter can be located at any position within a line comments are not part of ANSI C The result of the following valid ANSI C program will be incorrect if qcpluscmt is specified main int i 2 printf i n i 2 1 The correct answer is 2 2 divided by 1 When qcpluscmt is specified the result is 3 2 plus 1 The preprocessor handles all comments in the following ways e If the C option is not specified all comments are removed and replaced by a single blank e If the C option is specified comments are output unless they appear on a preprocessor directive or ina macro argument e If E is specified continuation sequences are recognized in all comments and are output e If P is specified comments are recognized and stripped from the output forming concatenated output lines A comment can span multiple physical source lines if they are joined into one logical source line through use of the backslash character You can represent the backslash character by a trigraph 7 Example of C Comments The following examples show the use of C comments Appendix A Compiler Options 247 A comment that spans two physical source lines A comment that spans two physical source lines
356. has no static members or non inline member functions and that has not been used in the declaration of an object function or class is local to its translation unit If the declaration of an identifier has the keyword extern and if a previous declaration of the identifier is visible at file scope the identifier has the same linkage as the first declaration External linkage occurs where identical identifiers in separately compiled files refer to the same data object or function The following kinds of identifiers have external linkage e Identifiers with file or block scope that have the keyword extern in their declarations If a previous declaration of the identifier is visible at file scope the identifier has the same linkage as the first declaration For example a variable or function that is first declared with the keyword static and is later declared with the keyword extern has internal linkage e Function identifiers declared without storage class specifiers e Object identifiers that have file scope declared without a storage class specified Storage is allocated for such object identifiers e Static class members and non inline member functions Identifiers declared with the keyword extern can be defined in other translation units No linkage occurs where each identical identifier refers to a unique object The following kinds of identifiers have no linkage e Identifiers that do not represent an object or a function incl
357. he qro option sets the storage type of string literals to read only and the qnoro option makes string literals writable Note Because a character constant can store only 1 byte avoid assigning multibyte characters to character constants Only the last byte of a multibyte character constant is stored Use a wide character representation instead Wide character string literals and constants must be prefixed by L For example wchar_t a L wide_char_string wchar_t b L c String literals and character constants are described in AIX Version 4 Language Reference The and operators preprocessor directives and macro definitions are also described there Preprocessor Directives The following preprocessor directives permit multibyte character constants and string literals e define e pragma comment e include These and other preprocessor directives are described in AIX Version 4 Language Reference Macro Definitions Because string literals and character constants can be part of define statements multibyte characters are also permitted in both object like and function like macro definitions Compiler Options Multibyte characters can appear in the compiler suboptions that take file names as arguments e key e oOfile_ name e B prefix e Fconfig_file stanza e directory e Ldirectory The D name definition option permits multibyte characters in the definition of the macro name In the following example the fi
358. he count excludes xx the digits 0 through 9 include lt stdio h gt define SIZE 3 int main void static char strings SIZE ab c5d e5 int is int letter_count 0 char pointer for i 0 i lt SIZE i for each string for each each character for pointer strings i pointer 0 pointer if a number if pointer gt 0 amp amp pointer lt 9 continue letter _count printf letter count d n amp quot letter count The program produces the following output letter count 5 Compare this program with the third program in which uses the break statement to perform a similar function Related Reading do A do statement repeatedly runs a statement until the test expression evaluates to 0 Because of the order of processing the statement is run at least once Me cho statement while expression t 148 C for AIX Users Guide The body of the loop is run before the controlling while clause is evaluated Further processing of the do statement depends on the value of the while clause If the while clause does not evaluate to 0 the statement runs again When the while clause evaluates to 0 the statement ends The controlling expression must be evaluate to a scalar type A break return or goto statement can cause the processing of a do statement to end even when the while clause does not evaluate to 0 Relat
359. he expression can contain defined macros No other identifiers can appear in the expression e The constant expression can contain the unary operator defined This operator can be used only with the preprocessor keyword if The following expressions evaluate to 1 if the identifier is defined in the preprocessor otherwise to 0 defined identifier defined identifier 352 C for AIX User s Guide For example if defined TEST1 defined TEST2 Note If a macro is not defined a value of O zero is assigned to it In the following example TEST must be a macro identifier if TEST gt 1 printf i d n i printf array i d n array i elif TEST lt 0 printf array subscript out of bounds n endi f Related Reading else Preprocessor Directive If the condition specified in the if ifdef or ifndef directive evaluates to 0 and the conditional compilation directive contains a preprocessor else directive the source text located between the preprocessor else directive and the preprocessor endif directive is selected by the preprocessor to be passed on to the compiler pr olse ststement p Related Reading The preprocessor endif directive ends the Aconditional compilation directive Appendix D Preprocessor Directives and Related Information 353 e amp ndif rea Related Reading error Preprocessor Directive A preprocessor error directive causes the pr
360. he heap specific memory management functions are provided just as they are for the regular versions Each debug version performs the same function as its non debug counterpart In Chapter 7 Writing C Programs 183 addition the debug version calls _uheap_check to check the heap used in the call and records the file and line number where the memory was allocated or freed You can then use _dump_al located or _dump_allocated_delta to display information about currently allocated memory blocks Information is printed to stderr You can use debug memory management functions for any type of heap including shared memory To use the debug versions specify the qheapdebug compiler option The C for AIX compiler then maps all calls to memory management functions regular or heap specific to the corresponding debug versions Note If you parenthesize the name of a memory management function the function is not mapped to the debug version Heap Checking Functions C for AIX also provides some new functions for validating user heaps uheapchk uheapset and _uheap_walk Each of these functions also has a non heap specific version that validates the default heap Both uheapchk and uheapset check the specified heap for minimal consistency uheapchk checks the entire heap while _uheapset checks only the free memory uheapset also sets the free memory in the heap to a value you specify uheap walk traverses the heap and provides information about each al
361. he initial value 438888834 unsigned long ss_number 438888834ul The following example defines the identifier sum as an object of type int The initial value of sum is the result of the expression a b extern int a b auto sum a b Related Reading enum An enumeration data type represents a set of values that you declare You can define an enumeration data type and all variables that have that enumeration type in one statement or you can separate the declaration of the enumeration data type from all variable definitions The identifier associated with the data type not an object is called an enumeration tag pe enum p E enumerator j oe identifier identifier Names the data type like the tag on a struct data type enumerator Provides the data type with a set of values gt sae aad a eee aS a a Infegral constant expression Each enumerator constant in the list has its own identifier and represents an integer value The integer value of an enumerator can be set implicitly by the position of the enumerator within the list or explicitly by assigning an integral_constant_expression value to that enumerator To conserve space enumerations may be stored in spaces smaller than that of an int Enumeration Constants When you define an enumeration data type you specify a set of identifiers that the data type represents Each identifier in this set is called an enumeration constant The valu
362. he order of the expression evaluation is not specified you can explicitly force the grouping of operands with operators by using parentheses In the expression atbx c d the and operations are performed before the because of precedence Further b is multiplied by c before it is divided by d because of associativity Special Cases Order of evaluation for function call arguments or for the operands of binary operators is not specified Avoid writing ambiguous expressions such as z x ty funcl y func2 i x i In the example above the order of evaluation of y and funcl y is not defined In fact they might not even be evaluated in the same order at different optimization levels Do not write code that depends on a particular order of evaluation of operators that have the same precedence The order of grouping operands with operators in an expression containing more than one instance of an operator with both associative and commutative properties is not specified The operators that have the same associative and commutative properties are amp and The order of evaluation for the operands of the logical AND amp amp and OR operators is always left to right If the operand on the left side of a amp amp operator evaluates to a O zero the operand on the right side is not evaluated If the opernad on the left side of a operator evaluates to a non zero value the operator on the right side is not
363. he order that they are to be directed to the appropriate compiler program Two exceptions to the rules of conflicting options are the Idirectory and Lairectory options which have cumulative effects when they are specified more than once In most cases conflicting or incompatible options are resolved according to the precedence shown in the following figure See orerriges Conese SVeITIaGess Conf igurat ion FfSrrices Default file line file settings Copyright IBM Corp 1995 1999 217 Most options that do not follow this scheme are summarized in the following table Option ___Conficting Options Resowion a e a E a e a S E e D a e a E angen seins sw Compiler Options and Their Defaults This page lists all C for AIX compiler options specifying each option s type and if it exists default value Where a appears beside the default value for a compiler option see the description for that option for special notes regarding the default value To get detailed information on any option listed click on the that option s name in the table OptionName Tye Dett Description 4 on page 231 flag Traces the compilation without doing anything 32_64 on page 231 qopt Selects 32 or 64 bit compiler mode qopt Enables destructive copy operations for structures and unions qopt See Specifies which type based aliasing is to be used during optimization align on page 234 qopt align full Speci
364. he switch statement ee identiese slemen In the examples below the label is both the identifier and the colon character at the beginning of each line comment_complete null statement label test_for_null if NULL pointer Related Reading Statement Blocks A block statement or compound statement lets you group any number of data definitions declarations and statements into one statement All definitions declarations and statements enclosed within a single set of braces are treated as a single statement You can use a block wherever a single statement is allowed Type detindien fe scope dete decleretion Block scope dete deckretion Definitions and declarations must come before the statements in a statement block Redefining a data object inside a nested block hides the outer object while the inner block runs However defining several variables that have the same identifier can make a program difficult to understand and maintain You should avoid redefining identifiers within nested blocks If a data object is usable within a block and its identifier is not redefined all nested blocks can use that data object Initialization of an auto or register variable occurs each time the block is run from the beginning If you transfer control from one block to the middle of another block initializations are not always performed You cannot initialize an extern variable within a block
365. hnical Reference Volumes 1 and 2 Base Operating System and Extensions Refer to the Subroutines Overview in AIX Version 4 General Programming Conceptsfor general information about library functions The macro NULL defined in the usr include stddef h header file expands to the null pointer constant void 0 4 1 5 The assert macro defined in the usr include assert h header file writes the following message to standard error and stops the program 4 2 Assertion failed expression file file name line line number In the error message file name is the name of the source file and line_number is the source line number of the assert statement The character testing ctype functions isalnum isalpha iscntrl islower isprint and isupper test for the following characters 4 3 1 isalnum The alphanumeric characters A Z a z and 0 9 isalpha The alphabetic characters A Z and a z iscntrl The nonprinting characters and any control character ASCII 0 31 or 127 islower The lowercase characters a z isprint The alphanumeric punctuation and space printing characters isupper The uppercase characters A Z After a domain error EDOM the mathematics functions return the value NaN 4 5 1 The mathematics functions set the integer expression errno to the value of the macro ERANGE on underflow range errors The usr include sys errno h header file declares the errno variable and defines a constant for each of the possib
366. ialization of auto aggregate variables Related Reading Exceptions to ansi C Addressed by classic C Exceptions to the ansi mode addressed by classic are as follows e Tokenization page ea e Preprocessing Directives page kes e Macro Expansion page Lea e Text Output Tokenization Tokens introduced by macro expansion may be combined with adjacent tokens in some cases Historically 164 C for AIX Users Guide this effect was caused by the text based implementations of older preprocessors and because in older implementations the preprocessor was a separate program whose output was passed on to the compiler For similar reasons tokens separated only by a comment may also be combined to form a single token Here is a Summary of how tokenization of a program compiled in classic mode is performed e Ata given point in the source file the next token is the longest sequence of characters which could possibly form a token For example i j is tokenized as i j even though i jis the intended tokenization e lf the token formed is an identifier and it is a macro name the macro is replaced by the text of the tokens specified on its define directive Each parameter is replaced by the text of the corresponding argument Comments are removed from both the arguments and the macro text e Scanning is resumed at the first step from the point at which the macro was replaced as if it were part of the original program e
367. iations are described below x1c128 cc128 xlc_r cc_r xIc_r4 cc_r4 xlc_r7 cc_r Related Reading All 128 suffixed invocation commands are functionally similar to their corresponding base compiler invocations They specify the qldbl128 option which increases the length of long double types in your program from 64 to 128 bits All _r suffixed invocations are functionally similar to their corresponding base compiler invocations but set the macro name D_THREAD_SAFE and invoke the added compiler options e L usr lib threads e Lusr lib dce e icr e ipthreads e qthreaded Use the _r suffixed invocations when compiling with the qsmp compiler option or if you want to create either Posix or AIX DCE threaded applications Use _r4 suffixed invocations to provide compatibility between DCE applications written for AIX Version 3 2 5 and AIX Version 4 They link your application to the correct AIX Version 4 DCE libraries providing compatibility between the latest version of the pthreads library and the earlier versions supported on AIX Version 3 2 5 On AIX 4 3 use _r7 suffixed invocations to compile and link applications conforming to DRAFT 7 of the Posix threads standard Otherwise the compiler will by default compile and link applications conforming to the current Posix threads standards On AIX 4 3 use _r7 suffixed invocations to compile and link applications conforming to DRAFT 7 of the Posix threads standard Otherwise th
368. iative and commutative and the order of grouping operands with operators can affect the result of the expression separate the expression into several expressions For example the following expressions could replace the previous expression if the called functions do not produce any side effects that affect the variable a a b a c a t d Integer overflows are ignored Division by zero and floating point exceptions are implementation dependent Related Reading Operands Most expressions can contain several different but related types of operands The following type classes described related types of operands integral Character objects and constants objects having an enumeration type and objects having the types short int long long long unsigned short unsigned int unsigned long or unsigned long long arithmetic Integral objects listed above and objects having the types float double long double and long float scalar Arithmetic objects listed above and pointers to any object type aggregate Arrays structures and unions Many operators cause conversions from one data type to another Related Reading Chapter 6 The C Language 69 Ivalues An value is an expression that represents an object A modifiable Ivalue is an expression representing an object that can be changed It is typically the left operand in an assignment expression For example arrays and const objects are not modifiable lvalue
369. ibs L lib profiled L usr lib profiled hdlibs L usr vac lib lhmd options qansialias qldbl128 qthreaded D_ THREAD SAFE D_VACPP MULTI _ standard c compiler aliased as cc_r AIX Threads cc_r use DEFLT crt lib crt0 o 478 C for AIX Users Guide mcrt gcrt libraries proflibs hdlibs options Clz8 r cc128 r Use crt mcrt gcrt libraries proflibs hdlibs options xXIC C compiler xlC_r use crit mcrt gcrt options libraries2 proflibs hdlibs a l1ib mcert0 o lib gcrt0 o L usr lib threads lpthreads lc L lib profiled L usr lib profiled L usr vac lib 1hmd qlanglvl extended qnoro qnoroconst qthreaded D_ THREAD SAFE D_VACPP MULTI _ DEFLT lib crt0 o l1ib mcrt0 o lib gcrt0 o L usr lib threads Ipthreads 1c128 1c L lib profiled L usr lib profiled L usr vac lib 1hmd qlanglvl extended qnoro qnoroconst qldb1128 qthreaded D_ THREAD SAFE D_VACPP MULTI _ jased as x1C_r AIX Threads DEFLT lib crt0 o l1ib mcrt0 o lib gcrt0 o qansialias qthreaded D THREAD SAFE D VACPP MULTI _ L usr lib threads L usr vacpp 1ib 1C lpthreads 1lm lc L usr vacpp 1ib profiled L lib profiled L usr lib profiled L usr vac 1ib 1hC 1hmd x x1C C compiler with 128 bit long double aliased as x1C128 r AIX Threads x1C128 r use crt mcrt gcrt libraries2 proflibs hdlibs options standard c compiler xlc_r4 use crt mcert gcrt libraries proflibs hdli
370. ic library file Id command only Specify the register allocation spill area Specify if and how parallelized object code is generated Choose code optimization options Generate information used by the fdpr performance tuning utility Set inlining options inline on page 277 Set rounding of single precision float operations Detect and trap oe sll _ Appendix A Compiler Options 229 Generate bind time type checking Choose type based aliasing during optimization Perform optimizations that assume errno is not modified by system calls Related Reading 230 C for AIX User s Guide Compiler Options Reference Option Type Default Value pragma options e Syntax Purpose Traces the compilation without invoking anything This option previews the compilation steps specified on the command line When the xlc command is issued with this option it names the programs within the preprocessor compiler and linkage editor that would be invoked and the options that would be specified to each program The preprocessor compiler and linkage editor are not invoked Notes The option overrides the v option It displays the same information as v but does not invoke the compiler Information is displayed to standard output Use this command to determine commands and files will be involved in a particular compilation It avoids the overhead of compiling the source code and overwriting any exis
371. ies the cache configuration to match that of the compiling machine cost cycles Specifies in instruction cycles the estimated performance penalty that results from a cache miss The compiler uses this value when deciding whether or not to perform an optimization that might result in extra cache misses level evel Specifies the level of cache affected where eve can be 1 Level 1 cache 2 Level 2 cache or the translation look aside buffer in a machine that has no level 2 cache 3 Translation look aside buffer in a machine that has a level 2 cache If a machine has more than one level of cache use a separate qcache option to describe each cache line bytes Specifies the line size of the cache in bytes size Kbytes Specifies the total size of the cache in Kbytes Appendix A Compiler Options 243 Suboption Description type cache_type Specifies the type of cache to which the above settings apply where cache_type can be Corc Combined data and instruction cache Dord Data cache lor i Instruction cache Use the following guidelines when specifying qcache suboptions Specify information for as many configuration parameters as possible If the target execution system has more than one level of cache use a separate qcache option to describe each cache level If you are unsure of the exact size of the cache s on the target execution machine specify an estimated cache size on the small side It is better to leave some cache memory un
372. ifier Some common uses for pointers are e To access dynamic data structures such as linked lists trees and queues e To access elements of an array or members of a structure e To access an array of characters as a string e To pass by reference the address of a variable to a function By referencing a variable through its address a function can change the contents of that variable Pointers occupy 4 bytes of data storage in 32 bit mode and 8 bytes in 64 bit mode Declaring a Pointer A pointer is declared by placing an asterisk after the data type specifier and before the identifier The following example declares pcoat as a pointer to an object having type long extern long pcoat If the keyword volatile appears before the the declarator describes a pointer to a volatile object If the keyword volatile comes between the and the identifier the declarator describes a volatile pointer The keyword const operates in the same manner as the volatile keyword described In the following example pvolt is a constant pointer to an object having type short Short const pvolt The following example declares pnut as a pointer to an int object having the volatile qualifier extern int volatile pnut The following example defines psoup as a volatile pointer to an object having type float float volatile psoup The following example defines pfowl as a pointer to an enumeration object of type bird enum bird pfowl The n
373. ifying the types of libraries that are searched for static or dynamic linking Default The default is to search only the C library Ic Example To compile myprogram c and include the Task Library libtask a and the Complex Mathematics Library libcomplex a enter xlc myprogram c Itask lcomplex Related Reading Er langlvl Option Type Default Value pragma options langlvl ansi LANGIvl suboption Syntax qlanglvl suboption suboption LANG lvl suboption suboption Purpose Selects the C language level used for compilation Default The default language level is ansi when you invoke the compiler using the xlc or c89 command The default language level is extended when you invoke the compiler using the cc command 286 C for AIX User s Guide You can use either of the following preprocessor directive styles to specify the language level used when compiling your C source program pragma options langlvl suboption suboption pragma langlv1 suboption The pragma directive must appear before any noncommentary lines in the source code Notes Language level suboptions can be specified using an abbreviation of the complete suboption name In the list below the minimum suboption specification is shown with uppercase characters Suboption names can be entered using either uppercase or lowercase characters Suboption Description ANSI Compilation conforms to the ANSI language level standard SAAL2
374. igned on their natural boundaries Long types and pointer types are word aligned in 32 bit mode and doubleword aligned in 64 bit mode Additional spaces could be used for padding members The alignment for qalign twobyte and qalign mac 68k are not supported in 64 bit mode Structures are aligned according to the strictest aligned member This remains unchanged from 32 bit mode Because of the padding introduced by the member alignment structure alignment may not be exactly the same as in the 32 bit mode This is especially important when you have arrays of structures which contain pointer or long types The member alignment will change most likely leading to the structure alignment to change to doubleword alignment if there are no long long types double types and long double types Bitfields Structure bitfields are limited to 32 bits and can be of type signed int unsigned int or plain int Bit fields are packed into the current word Adjacent bit fields that cross a word boundary will start at storage unit This storage unit is a word in power and full alignment halfword in the mac68k and twobyte alignment and byte in the packed alignment 64 bit bitfields are not supported In 32 bit mode non integer bitfields are tolerated but not respected only in the C extended language level If you use long bit fields in 64 bit mode their exact alignment may change in future versions of the compiler even if the bitfield is under 32 bits in
375. iled 64 bit objects you must link these objects using 64 bit mode Related Reading aggrcopy Option Type Default Value pragma options fp aopton Seema Syntax gaggrcopy overlap gaggrcopy noover lap Purpose Enables destructive copy operations for structures and unions Notes If the qaggrcopy nooverlap compiler option is enabled the compiler assumes that the source and destination for structure and union assignments do not overlap This assumption lets the compiler generate faster code Default Setting The default setting of this option is qaggrcopy nooverlap when compiling to the ANSI SAA and SAAL2 language levels The default setting of this option is qaggrcopy overlap when compiling to the EXTENDED and CLASSIC language levels Programs that do not comply to the ANSI C standard as it pertains to non overlap of source and destination assignment may need to be compiled with the qaggrcopy overlap compiler option 232 C for AIX User s Guide Example xlc myprogram c qaggrcopy nooverlap Related Reading Option Type Default Value pragma options ansi typeptr noallptrs noaddrtaken ALIAS suboption suboption Syntax qalias suboption suboption ALIAS suboption suboption Purpose Requests the compiler to apply aliasing assertions to your compilation unit The compiler will take advantage of the aliasing assertions to improve optimizations where possible unless you specify otherwise Not
376. iler listing to find the variables that have different alignment settings Your code should not depend on the offset or alignment of members within a structure Use the offsetof macro defined in the usr include stddef h header file to determine the offset of members in a macro This macro is described in the AlX Version 4 Files Reference Declaring Structure Types and Variables To define a structure type and a structure variable in one statement put a declarator and an optional initializer after the type definition To specify a storage class specifier for the variable you must put the storage class specifier at the beginning of the statement For example static struct int street_no char street_name char city char prov char postal_ code perm_address temp address Because this example does not name the structure data type perm_address and temp address are the only structure variables that will have this data type Putting an identifier after struct lets you make additional variable definitions of this data type later in the program The structure type or tag cannot have the volatile qualifier but a member or a structure variable can be defined as having the volatile qualifier For example static struct classl char descript 20 volatile long code Short complete volatile filel file2 Struct classl subfile This example qualifies the structures filel and file2 and the structure member subfile code
377. imary expression must be an instance of a type of structure or union and the identifier must name a member of that structure or union The result is the value associated with the named structure or union member The result is an lvalue if the first expression is an lvalue Some sample dot expressions roster num name roster num name 1 When you use the arrow operator the primary expression must be a pointer to a structure or a union and the identifier must name a member of the structure or union The result is the value of the named structure or union member to which the pointer expression refers In the following example name is an int roster gt name Related Reading Chapter 6 The C Language 119 Unary Operators Increment The increment operator adds 1 to the value of a scalar operand or if the operand is a pointer increments the operand by the size of the object to which it points The operand receives the result of the increment operation The operand must be a modifiable lvalue of arithmetic or pointer type You can put the before or after the operand If it appears before the operand the operand is incremented and then the incremented value is used in the expression If you put the after the operand the value of the operand is used in the expression before the operand is incremented For example play playl play2 is equivalent to the following three expressions playl playl
378. imit to the number of declarators that can modify a structure union or arithmetic type 3 5 4 Related Reading Implementation Dependency Statements F 3 12 There is no limit to the number of case values in a switch statement 3 6 4 2 RELATED REFERENCES Related Reading CTR Implementation Dependency Preprocessing Directives F 3 13 The value of a single character character constant in a constant expression that controls conditional inclusion does not match the value of the same character constant in the execution character set 3 8 1 A single character character constant in a constant expression that controls conditional inclusion can have a negative value 3 8 1 Headers are identified by the directive include lt file_name gt and are stored under usr include 3 8 2 User defined include file names can be specified in double quotation marks 3 8 2 The mapping between the name specified in the include directive and the external source file name is one to one Multibyte characters are permitted in the include directive 3 8 2 The definitions of the _ DATE __ and__TIME___ predefined macros are always defined to the system date and time 3 8 8 454 C for AIX User s Guide Related Reading Implementation Dependency Library Functions F 3 14 All of the C library functions are part of the AIX Base Operating System BOS Runtime Services and are described in detail in the AlX Version 4 Tec
379. in aggregates members are aligned according to their type The table below summarizes size and alignment information for each type Type Size and Alignment for the RISC System 6000 System double doubleword aligned if qalign natural Otherwise word aligned long double long doubleword aligned if with qlongdouble or qldbl128 qalign natural Otherwise word option aligned Notes 1 The entire object is aligned on the same boundary as its most strictly aligned member 2 Each member is assigned the lowest available offset with the appropriate alignment internal padding 3 The object s size is increased if necessary to make it a multiple of the size of its most strictly aligned member For example if the object contains a word it is padded to a word boundary On the RISC System 6000 system if a double is the first member of a struct it is 8 byte doubleword aligned If a long double is the first member of a struct it is 16 byte aligned Bit Fields for RISC System 6000 Format The following rules apply when you are laying out bit fields in structs e structs containing bit fields are 4 byte word aligned e Bit fields can be at most 32 bits long e Bit fields are packed into the current word If a bit field would cross a word boundary it starts at the next word boundary e A bit field of width zero causes the bit field that immediately follows it to be aligned at the next word boundary If the zero width bit fiel
380. ined object are exactly the same as if the object were defined by explicitly listing the data type associated with the identifier The following statements declare LENGTH as a synonym for int then use this typedef to declare length width and height as integral variables typedef int LENGTH LENGTH length width height The following declarations are equivalent to the above declaration int length width height Similarly you can use typedef to define a struct type For example typedef struct int scruples int drams int grains WEIGHT The structure WEIGHT can then be used in the following declarations WEIGHT chicken cow horse whale Related Reading Data Type Qualifiers Qualifier Description const Explicitly declares a data object as a data item that cannot be changed Its value is set at initialization You cannot use const data objects in expressions requiring a modifiable lvalue For example a const data object cannot appear on the left hand side of an assignment statement Chapter 6 The C Language 115 volatile Maintains consistency of memory access to data objects lt tells the compiler that the variable should always contain its current value even when optimized so that the variable can be queried when an exception occurs Volatile objects are read from memory each time their value is needed and written back to memory each time they are changed The volatile qualifier is useful for data objects
381. ing and working with the AlXwindows Desktop lt also introduces system commands for securing files using storage media and customizing environment files e AIX Version 4 Getting Started SC23 2527 Contains information for users who have little or no experience with the AIX operating system It introduces basic system commands covering tasks such as starting and stopping the system using a keyboard or mouse logging in and out identifying and using the various user interfaces and running basic file commands e AIX Version 4 Commands Reference SBOF 1851 A collection of volumes that contain descriptions and examples of AIX commands and their available flags e AIX Version 4 General Programming Concepts SC23 2533 and SC23 2490 Discusses the operating system from a programming perspective e AIX Version 4 Technical Reference Volumes 1 and 2 Base Operating System and Extensions SC23 2614 and SC23 2615 Provides reference information about system calls subroutines macros and statements associated with the AIX base operating system runtime services and device services Copyright IBM Corp 1995 1999 xvii Non IBM Publications The C language is a well established programming language The following standards describe it e ANSIISO IEC 9899 1990 1992 Presents the ANSI ISO standard for the C language This document has officially replaced American National Standard for Information Systems Programming Language C X3 159 1989 as the AN
382. ing the structure or union is affected _align 128 struct S int i3 sizeof struct S 128 struct S sarray 10 sarray is aligned on 128 byte boundary with sizeof sarray 1280 x Struct S _align 64 svar error alignment of variable is smaller than alignment of type x struct S2 struct S sl int as s2 s2 is aligned on 128 byte boundary with sizeof s2 256 bytes x Applying __align to an array AnyType _ align 64 arrayA 10 Only arrayA is aligned on a 64 byte boundary and elements within that array are aligned according to the alignment of AnyType Padding is applied after the back of the array and does not affect the size of the array member itself x Applying __align where size of variable alignment differs from size of type alignment __align 64 struct S int i3 struct S _ align 32 sl error alignment of variable is smaller than alignment of type x Struct S _ align 128 s2 s2 is aligned on 128 byte boundary x struct S _align 16 s3 10 error int _align 1 s4 error x _ align l struct S int i error Related Reading Appendix H RISC System 6000 Alignment Rules 443 444 C for AIX User s Guide Appendix I Implementation Dependencies Overview The behavior of some features of the C language depends on the particular C compiler used This and related pages describe these C for AIX implementation specific dependencies Or AIX Comoie aa
383. ing your program Bear in mind that specifying this option can significantly increase the memory requirements and running time of your program Memory Allocation Fill Pattern Some debug functions set all the memory they allocate to a specified fill pattern This lets you easily locate areas in memory that your program uses The debug_malloc debug_realloc and debug_umalloc functions sets allocated memory to a default repeating OxAA fill pattern To enable this fill pattern export the HD FILL environment variable The debug _free function sets all free memory to a repeating OxFB fill pattern Chapter 7 Writing C Programs 195 Skipping Heap Checks Each debug function calls heap check or uheap_ check to check the heap Although this is useful it can also increase your program s memory requirements and decrease its execution speed To reduce the overhead of checking the heap on every debug memory management function you can control how often the functions check the heap with the HD SKIP environment variable You will not need to do this for most of your applications unless the application is extremely memory intensive Set HD SKIP like any other environment variable The syntax for HD SKIP is set HD SKIP increment start where increment Specifies how often you want the debug functions to check the heap start Optional Use this parameter to start skipping heap checks after start calls to debug functions Note The comma s
384. instruction causing the exception and decode it find inst sets the static variables that indicate the instruction location kind and registers if find_instr unsigned int scp gt sc_jmpbuf jmp_context iar fputs SIGTRAP handler failed to find exception point n stderr Note that because the exception might have occurred in a subroutine that was not compiled with the flttrap option jt may be desirable simply to ignore the exception by Clearing the exception bits and returning exit 43 Examine the floating point status and control register for x enabled exceptions Customize each case below if fpstat amp TRP_INVALID FP_INVALID TRP_INVALID FP_INVALID fprintf stderr FP invalid operation operation s location x n opcode fpe loc Consider an invalid operation an unrecoverable error By examining other bits in the status and control register we can identify the specific invalid operation that occurred for example zero divided by zero Using the kind of operation we can examine the source operands If the instruction has any result registers they have not been modified F exit 44 if fpstat amp TRP_OVERFLOW FP_OVERFLOW TRP_OVERFLOW FP_OVERFLOW fprintf stderr FP overflow operation s location x n opcode fpe loc Note that the result register in an overflow contains a correctly rounded normalized number but 1536
385. int value The first line of the following example declares the enumeration tag grain The second line defines the variable g_ food and gives variable g_ food the initial value of barley 2 enum grain oats wheat barley corn rice enum grain g_food barley The type specifier enum grain indicates that the value of g food is a member of the enumerated data type grain Defining an Enumeration Type and Enumeration Objects in the Same Statement You can define a type and a variable in one statement by using a declarator and an optional initializer after the type definition To specify a storage class specifier for the variable you must put the storage class specifier at the beginning of the declaration For example register enum score poor l average good rating good This example is equivalent to the following two declarations enum score poor l average good register enum score rating good Both examples define the enumeration data type score and the variable rating rating has the storage class specifier register the data type enum score and the initial value 3 or good Combining a data type definition with the definitions of all variables having that data type lets you leave the data type unnamed For example enum Sunday Monday Tuesday Wednesday Thursday Friday Saturday weekday defines the variable weekday which can be assigned any of the specified enumeration constants Related Reading
386. inter to the concatenated string string Example This example contains a programming error The bufferl1 object is not large enough to store the result after the string program is concatenated include lt stdlib h gt include lt stdio h gt include lt string h gt define SIZE 10 int main void char xbufferl char ptr bufferl char malloc SIZE strcpy bufferl computer ptr strcat bufferl program printf bufferl s n bufferl return 0 BRK KEK RRR KKK kk k k k ER KERR RRR ERR KK ERR ERE RRR KEKE RRR ERK ERK EKER ERE Kk KK EKER Kk k The output should be similar to End of allocated object 0x00073c80 was overwritten at 0x00073c8a The first eight bytes of the memory block in hex are 636F6D7075746572 This memory block was re allocated at line number 12 in strcat c Heap state was valid at line 13 of strcat c Memory error detected at line 15 of strcat c KA KKK KK RE KR ERK ERK EK RRR KKK KER KER KR KK EKER RRR K Kk Kk Kk KK k ERR RE RK EKER ERE kk kk kkk kk Related Reading 420 C for AIX Users Guide _debug_strcpy Copy Strings Format include lt string h gt char debug strcpy char stringl const char string2 const char file size t line Language Level Extension _debug_strcpy is the debug version of strcpy Like strcpy it copies string2 including the ending null character to the location specified by stringl _debug_sitrcpy validates the heap after
387. ion specification is a sequence of this form 4 12 3 5 r type n ee ee apmien where hyphen Is the character It puts padding on the right of the converted value instead of on the left if needed width Is the minimum field width precision Is the maximum field width Appendix Implementation Dependencies Overview 459 type Is specified by one or two conversion characters The characters and their meanings are D Represents the date in the format m d y for example 01 31 92 e Represents the day of the month as a decimal number 1 to 31 with a leading space if needed E Represents the combined alternative era year and name for the locale in 0 N format h Represents the abbreviated month name for the locale for example Jan N Is a new line character N Represents the alternative era name for the locale 0 Represents the alternative era year for the locale rr 12 hour clock format with AM PM notation which is the same as 1 M S AM PM t Is a tab character T 24 hour clock time in the format H M S for example 16 55 15 Refer to the AIX Version 4 Technical Reference Volumes 1 and 2 Base Operating System and Extensionsfor more information about time and date formatting and the strftime function Character Testing and Case Mapping The execution character set follows the ASCII collating sequence 4 3 and 4 11 4 4 e The control characters representing horizontal ta
388. ion that is directly recursive the call to the function from within itself is not inlined For example given three functions to be inlined A B and C where 1 A calls B 2 B calls C 3 C calls back to B Chapter 7 Writing C Programs 203 the following inlining takes place 1 The call to B from A is inlined 2 The call to C from B is inlined 3 The call to B from C is not inlined because it is made from within an inline expansion of B itself Related Reading on nade Z _Inline inline inline C for AIX provides keywords that you can use to specify functions that you want the compiler to inline e Inline e inline e inline For example _Inline int catherine int a causes catherine to be inlined meaning that code is generated for the function rather than a function call The inline keywords also implicitly declare the function as static Using the inline specifiers with data generates an error By default function inlining is turned off and functions qualified with inline specifiers are treated simply as static functions To turn on function inlining specify either the qinline or Q compiler options If you turn optimization on O Oi becomes the default Recursive functions functions that call themselves are inlined for the first occurrence only The call to the function from within itself is not inlined You can also use the qinline or Q compiler options to automatically inline all functions
389. irectly to the current shell Then the shell command interprets it as a command and runs it 4 10 4 5 Note The system function runs only Bourne Shell bsh commands The results are unpredictable if the string parameter is not a valid bsh command strerror Function The format of the error message output of the strerror function is the same as for perror 4 11 6 2 The contents of the error message strings returned by a call to the strerror function is the same as for perror 4 11 6 2 Related Reading Implementation Dependency Locale Specific Behavior F 4 The C for AIX compiler defines the following locale specific behavior e The local time zone and daylight saving time are set by the operating system 4 12 1 e The era for the clock function starts when the process containing the program is started 4 12 2 1 e The locale determines the characters of the execution set Some locales contain characters other than those required by the C standard 2 2 1 e The direction of printing is left to right 2 2 2 e The decimal point character is locale specific For the United States English locale it is the period 4 1 1 e The format of the time and date is specified by the format parameter of the strftime function It is a character string containing two types of objects plain characters that are simply placed in the output string and conversion specifications for presenting the time and date in a readable form Each convers
390. is exited the objects are no longer available for use If an auto object is defined within a function that is recursively invoked memory is allocated for the object at each invocation of the block Related Reading A a JOLO Of Ode Cd Examples Using auto Storage Classes The following program shows the scope and initialization of auto variables The function main defines two variables each named auto _ var The first definition occurs on line 10 The second definition occurs in a nested block on line 13 While the nested block is running only the auto var created by the second definition is available During the rest of the program only the auto var created by the first definition is available ERK kk kk RRR kk kk k RE RRR RK ER RRR k k k k k RRR EKER ERK EKER RE xx Example illustrating the use of auto variables KKK KKK KKK KEK KEE KR ERK ERK ER KER ER KK ERK ER KER ERK EREREREREE int main void 1 2 3 4 5 include lt stdio h gt 6 7 8 d 9 void call_func int passed_var 10 auto int auto var 1 first definition of auto var 11 12 13 int auto_var 2 second definition of auto var 14 printf inner auto var d n auto var 15 16 call_func auto_ var 17 printf outer auto var d n auto var Chapter 6 The C Language 107 18 return 0 19 20 21 void call_func int passed var 22 23 printf passed var d n passed var 24 passed var
391. isables automatic setting of the qarch and qtune compiler options You can use qarch suboption with qtune suboption qarch suboption specifies the architecture for which the instructions are to be generated and qtune suboption specifies the target platform for which the code is optimized Default The default setting of the qarch option depends on the setting of the qtune option If qtune is specified without qarch the compiler uses qarch com Appendix A Compiler Options 237 If qarch is specified without qtune the compiler uses the default tuning option for the specified architecture Listings will show only TUNE DEFAULT To find the actual default qtune setting for a given qarch setting refer to EAcceptahle Compiler Modd Example To specify that the executable program testing compiled from myprogram c is to run on a computer with a 32 bit PowerPC architecture enter xlc o testing myprogram c qgarch ppc Related Reading assert Option Type Default Value pragma options aopton toast Syntax qassert suboption Purpose Requests the compiler to apply aliasing assertions to your compilation unit The compiler will take advantage of the aliasing assertions to improve optimizations where possible Notes This option is obsolete Use qalias in your new applications The compiler will apply aliasing assertions when you specify the following suboptions gASSert TYPeptr Pointers to differe
392. isolated_call directives in the source file ibm Ignores all IBM parallel processing directives in the source file such as pragma ibm parallel loop pragma ibm schedule etc omp Ignores all OpenMP parallel processing directives in the source file such as pragma omp parallel pragma omp critical etc The ignprag option is useful for detecting aliasing pragma errors Incorrect aliasing gives runtime errors that are hard to diagnose When a runtime error occurs but the error disappears when you use qignprag with the O option the information specified in the aliasing pragmas is likely incorrect This option is also useful for disabling parallel processing directives to ensure that a program works correctly in both sequential and parallel mode 2 4 C for AIX Users Guide Examples 1 To compile myprogram c and ignore any pragma isolated directives enter xlc myprogram c qignprag isolated 2 To compile myprogram c and ignore all parallel processing pragmas enter xlc myprogram c qignprag ibm omp Related Reading info Option Type Default Value pragma options Syntax qinfo qinfo all qinfo suboption suboption qnoinfo INFO INFO ALL INFO suboption suboption INFO RESET NOINFO Purpose Produces informational messages Notes Specifying qinfo or qinfo all turns on all diagnostic messages for all groups Specifying qnoinfo turns off all diagnostic messages You can use the pragma opti
393. itutions More than one pragma construct can be specified on a single pragma directive The compiler ignores unrecognized pragmas Some pragma directives as indicated in the list below must appear before any statements in the C source code The other pragma directives can be used throughout your program to affect a selected block of source code The C for AIX compiler lets you specify many compiler options as either command line options or as pragma statements In addition the C for AIX compiler recognizes the pragmas listed below Appendix D Preprocessor Directives and Related Information 363 Provides an inline version of function alloca This directive must appear before any statements in the C source code Sets the sign type of character data This directive must appear before any statements in the C source code Places a comment into the object file Lists identifiers not aliased to each other within the current scope of their use Identifies the expected frequency with which a block of code will be executed Specifies the file name of the precompiled header to be generated and or used Terminates the initial sequence of include directives being considered for precompilation Controls the diagnostic messages generated by the qinfo compiler option Lists functions that do not alter data objects visible at the time of the function call Selects the C language level for compilation This directive must appear before any
394. ive The pragma execution_frequency directive identifies the expected frequency with which a block of code will be executed This information is used by the compiler as hint to the optimizer ee pragma execution frequency frequency t The currently accepted value for frequency is very_low The probability of execution for the statement block in which the pragma resides is very close to nil This pragma has effect only if Appendix D Preprocessor Directives and Related Information 367 e the program is optimized e the pragma is placed inside statements with block scope such as if then else looping and switch statements A warning message is issued and the pragma ignored if it is placed outside of block scope Examples 1 In the following sample program execution is unlikely to branch through Block A int array int malloc 10000 if array NULL Block A pragma execution frequency very_low error 2 In the following sample program code Block B is marked as being infrequently executed indicating that Block C is most likely to be chosen during branching if Foo gt 0 pragma execution frequency very_low Block B doSomething else Block C doAnotherThing Related Reading pragma hdrfile Preprocessor Directive The pragma hdrfile directive specifies the file name of the precompiled header to be generated and or used ee prag
395. ized enums and ENUM RESET to reset the enum mapping rule to the rule that was in effect before the current mapping rule If no previous enum mapping rule was specified in the file the rule specified when the compiler was invoked is used A qenum reset option corresponding to the pragma options ENUM RESET directive does not exist Attempting to use qenum reset generates a warning message and the option is ignored Examples 1 One typical use for the reset suboption is to reset the enumeration size set at the end of an include file that specifies an enumeration storage different from the default in the main file For example the following include file small_enum h declares various minimum sized enumerations then resets the specification at the end of the include file to the last value on the option stack x File smal _enum h This enum must fit within an unsigned char type i pragma options enum smal enum e tag a b 255 enum e tag u_char_e var occupies 1 byte of storage Reset the enumeration size to whatever it was before pragma options enum reset The following source file int_file c includes small_enum h File int_file c Defines 4 byte enums pragma options enum int enum testing ONE TWO THREE enum testing test_enum various minimum sized enums are declared include small _enum h return to int sized enums small_enum h has reset the enum size enum sushi CALIF
396. k If debug_strncat detects a corrupted heap when it makes a call to heap check debug_sitrncat will report the file name file and line number line in a message Note debug_strncat checks only the current default heap Therefore this debug support will not check all heaps within applications that have multiple user heaps To use _debug_strncat you must compile with the debug memory qheapdebug compiler option This option maps all strncat calls to debug_strncat You do not have to change your source code in order for debug_strncat to verify the heap Note The qheapdebug option maps all calls to other string functions and all calls to memory management functions including a heap specific version to their debug counterparts To prevent a call from being mapped parenthesize the function name 422 C for AIX User s Guide Return Value _debug_strncat returns a pointer to the joined string string1 Example This example contains a programming error The buffer1 object is not large enough to store the result after eight characters from the string programming are concatenated include lt stdlib h gt include lt stdio h gt include lt string h gt define SIZE 10 int main void char xbufferl char ptr bufferl char malloc SIZE strcpy bufferl computer Call strncat with bufferl and programming ptr strncat bufferl programming 8 printf strncat bufferl s n bufferl return
397. ket e question mark For more information on the f compiler option refer to the Id command in the AIX Commands Reference Option Type Default Value pragma options e Syntax Fconfig file stanza Fconfig file F stanza Purpose Names an alternative configuration file for xlc Notes config file Specifies the configuration of your system to the compiler Appendix A Compiler Options 259 stanza Is the name of the command used to invoke the compiler This directs the compiler to the config_file under stanza for the description of the compiler environment This suboption is not required The default is a configuration file supplied at installation time called etc vac cfg Any file names or stanzas that you specify on the command line or within your source file override the defaults specified in the etc vac cfg configuration file Options specified with W option override options in the Fconfig_file configuration file The B t and W options override the F option Example To compile myprogram c using a configuration file usr tmp myvac cfg with an xlc stanza enter xlc myprogram c F usr tmp myvac cfg xlc Related Reading fdpr Option Type Default Value pragma options e a Syntax qfdpr qnofdpr Purpose Collects information about your program for use with the AIX fdpr Feedback Directed Program Restructuring performance tuning utility Notes You should compile your program with qfdpr be
398. kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkx Related Readin _debug_sircat Concatenate Strings Format include lt string h gt char debug strcat char stringl const char string2 const char file size t file Language Level Extension _debug_sircat is the debug version of strcat Like strcat it concatenates string2 to string and ends the resulting string with the null character _debug_sircat validates the heap after concatenating the strings and performs this check only when the target is within a heap _debug_strcat makes an implicit call to heap check If debug_strcat detects a corrupted heap when it makes a call to heap check debug _strcat will report the file name file and line number file in a message Note debug_strcat checks only the current default heap Therefore this debug support will not check all heaps within applications that have multiple user heaps To use _debug_strcat you must compile with the debug memory qheapdebug compiler option This option maps all strcat calls to debug_strcat You do not have to change your source code in order for _debug_strcat to verify the heap Appendix F C for AIX Debug Functions 419 Note The qheapdebug option maps all calls to other string functions and all calls to memory management functions including a heap specific version to their debug counterparts To prevent a call from being mapped parenthesize the function name Return Value _debug_sircat returns a po
399. kkkkkkkkkkkkkkkkkkkkkkx int max int a int b Function definition if a gt b return a else return b The first source file declares the function max but does not define it This is an external declaration a declaration of a function defined in source file 2 Four statements in main are function calls of max The lines beginning with a number sign are preprocessor directives that direct the preprocessor to replace the identifiers ONE TWO and THREE with the digits 1 2 and 3 The directives in the first source file do not apply to the second source file The second source file contains the function definition for max which is called four times in main After you compile the source files you can link and run them as a single program Related Reading External Structure of a C Program A source program consists of at least one source file You can compile a source program that consists of several source files by specifying all of the source files as input to the compiler invocation command Typically compiler invocation produces calls to both the compiler and the linkage editor and creates a single executable file as output For example to produce an executable file named testprog from three files testdata c testres c and testparm c you would enter xlc testdata c testres c testparm c o testprog You can also compile each source file separately by specifying the compiler option to invoke only the compiler to
400. l Processing OpenMP Run time Options for Parallel Processing Appendix F C for AIX Debug Functions _debug_calloc Allocate and Initialize Memory _debug_free Free Allocated Memory _debug_heapmin Free Unused Memory in the Default Heap _debug_malloc Allocate Memory _debug_memcpy Copy Bytes _debug_memmove Copy Bytes _debug_memset Set Bytes to Value _debug_realloc Reallocate Memory Block _debug_strcat Concatenate Strings _debug_strcpy Copy Strings _debug_strncat Concatenate Strings _debug_strncpy Copy Strings _debug_strnset Set Characters in String _debug_strset Set Characters in String _debug_ucalloc Reserve and Initialize Memory from User Heap _debug_uheapmin Free Unused Memory in User Heap _debug_umalloc Reserve Memory Blocks from User Heap Appendix G Built in Functions for PowerPC Processors Appendix H RISC System 6000 Alignment Rules Alignment Rules for Nested Aggregates Packed Alignment Rules MacIntosh and Twobyte Alignment Rules __align Specifier Appendix I Implementation Dependencies Overview C for AIX Compiler Limits eee Implementation Defined Behavior Implementation Dependency Translation F 3 1 Implementation Dependency Environment F 3 2 Implementation Dependency Identifiers F 3 3 Implementation Dependency Characters F 3 4 Implementation Dependency Integers F 3 5 Implementation Dependency Floating Point Types F 3 6
401. l Switches on all the following suboptions You can use the all option along with the no form of one or more of the other qchecksuboptions as a filter For example using xlc myprogram c qcheck al1 nonul provides checking for everything except for addresses contained in pointer variables used to reference storage If you use all with the no form of the options all should be the first suboption Appendix A Compiler Options 245 NULLptr NONULLptr Performs runtime checking of addresses contained in pointer variables used to reference storage The address is checked at the point of use a trap will occur if the value is less than 512 bounds nobounds Performs runtime checking of addresses when subscripting within an object of known size The index is checked to ensure that it will result in an address that lies within the bounds of the object s storage A trap will occur if the address does not lie within the bounds of the object DIVzero NODIVzero Performs runtime checking of integer division A trap will occur if an attempt is made to divide by zero Using the qcheck option without any suboptions turns all the suboptions on Using the qcheck option with suboptions turns the specified suboptions on if they do not have the no prefix and off if they have the no prefix You can specify the qcheck option more than once The suboption settings are accumulated but the later suboptions override the earlier ones The pr
402. l Treatment of Character and Aggregate Data Most numeric data types have counterparts across the three languages Character and aggregate data types require special treatment e Because of padding and alignment differences C structures do not exactly correspond to the Pascal RECORD data type e C character strings are delimited by a 0 character In Fortran all character variables and expressions have a length that is determined at compile time If Fortran passes a string argument to another routine it adds a hidden argument giving the length to the end of the argument list This length argument must be explicitly declared in C The C code should not assume a null terminator the supplied or declared length should always be used Use the strncat strncpm and strncpy functions of the C runtime library These functions are described in the AlX Version 4 Technical Reference Volumes 1 and 2 Base Operating System and Extensions e Pascals STRING data type corresponds to a C structure For example VAR s STRING 10 is equivalent to struct int length char str 10 js where length contains the actual length of STRING e The qmacpstr option converts Pascal string literals into null terminated strings where the first byte contains the length of the string e C and Pascal store array elements in row major order array elements in the same row occupy adjacent memory locations Fortran stores array elements in ascending stora
403. language Calls Stack Floor Interlanguage Calls Stack Overflow Interlanguage Calls Traceback Table ss Interlanguage Calls Type Encoding and Checking Sample Program C Calling Fortran ye ms Appendix A Compiler Options Resolving Conflicting Compiler Options Compiler Options and Their Defaults Lists of Compiler Options by Functional Groupings Options that Specify Compiler Characteristics Options that Specify Debugging Features Options that Specify Preprocessor Options Options that Specify Compiler Output maar Options that Specify the Compiler Object Code Produced Options that Specify Linkage Options Sr Compiler Options Reference l n 32 64 aggrcopy alias align ansialias arch assert atir B viii C for AIX User s Guide 186 188 189 189 190 191 195 197 197 198 2 199 199 199 200 201 201 202 207 207 207 208 209 210 210 211 211 See 213 213 213 214 214 214 sel7 217 218 226 226 22 228 228 229 230 231 231 231 232 233 234 236 237 238 238 239 bitfields brtl a amp bstatic bdynamic C C cache chars check compact cpluscmt D datalocal dataimported dbxextra digraph dollar dpcl E enum extchk f ra 4 fdor flag float flttrap fold fullpath G On n e a genpcomp genproto halt
404. lated Reading listopt Option Type Default Value pragma options Syntax qlistopt qnolistopt Purpose Produces a compiler listing that displays all options in effect at time of compiler invocation The listing will show options in effect as set by the compiler default configuration file and command line settings Option settings caused by pragma statements in the program source are not shown in the compiler listing Example To compile myprogram c to produce a compiler listing that shows all options in effect enter xlc myprogram c qlistopt Related Reading longlit Option Type Default Value pragma options Syntax qlonglit qnolonglit Purpose Changes implicit type selection in 64 bit mode to use larger data types where possible Notes This feature provides the same effect as suffixing all integer constants with I or L This option may be useful in porting to 64 bit situations where a signed long result is expected instead of unsigned int in expressions that contain literals For example 292 C for AIX User s Guide unsigned int ui 0 long l ui 1 In 32 bit mode I will be equal to 1 In 64 bit mode the value of becomes UINT_ MAX Forcing 1 into type signed long will provide the desired result Use this option with extreme caution as it implicitly changes the type of all unsuffixed integer constants that would otherwise have type int or unsigned int The following table shows implicit
405. le error conditions 4 5 1 When the fmod function has a second argument of zero a domain error EDOM is generated and NaN is returned 4 5 6 4 Signals The sigaction sigvec and signal functions of the C Library specify the action to take upon delivery of a signal These functions are described in the AIX Version 4 Technical Reference Volumes 1 and 2 Base Operating System and Extensions 4 7 1 1 Signals do not have parameters because they are not functions 4 7 1 1 The default handling and the handling at program startup for each signal recognized by the signal function are described with the sigaction sigvec and signal functions 4 7 1 1 The equivalent of signal sig SIG_DFL is performed before the call of a signal handler 4 7 1 1 Appendix Implementation Dependencies Overview 455 The default handling is reset if a SIGKILL signal is received by a handler specified to the signal function 4 7 1 1 Streams and Files The last line of a text stream does not require a terminating new line character 4 9 2 Space characters that are written out to a text stream immediately before a new line character appear when the stream is read back in 4 9 2 No null characters can be appended to data written to a binary stream 4 9 2 The file position indicator of an append mode stream is initially positioned at the end of the file 4 9 3 A write on a text stream does not cause the associated file to be truncated beyond that
406. le shows extern kx xx used by two functions x KK KKK Kk kkk kk kkk kk kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk include lt stdio h gt include lt string h gt char string 75 110 C for AIX Users Guide int length int main void void sort void printf Enter letters n scanf s string length strlen string sort printf The sorted string is s n string return 0 void sort void int Gap Is j Lemp for gap length 2 gap gt 0 gap 2 for i gap i lt length i for j i gap j gt 0 amp amp string j gt string j gap J gap temp string j string j string j gap string j gap temp When this program is run interaction with it could produce Output Enter letters Input zyfab Output The sorted string is abfyz Related Reading register The register storage class specifier indicates to the compiler that a heavily used variable such as a loop control variable within a block scope data definition or a parameter declaration should be allocated a register to minimize access time It is equivalent to the auto storage class except that the compiler places the object if possible into a machine register for faster access Note Because the C for AIX compiler optimizes register use it ignores the register keyword Most heavily used entities are generated by the compiler itself therefore register variables are given no special
407. lel constructs e Variables in private context are hidden from other threads Each thread has its own private copy of the variable and modifications made by a thread to its copy are not visible to other threads You can explicitly specify a shared or private context for a variable or you can let the compiler determine the default context of a variable according to the following rules e Variables with static storage duration are shared e Dynamically allocated objects are shared e Variables with automatic storage duration are private e All variables defined outside a parallel construct become shared when the parallel construct is encountered e Loop iteration variables are private within their loops The value of the iteration variable after the loop is the same as if the loop were run sequentially e Memory allocated by the alloca function within a parallel loop or any other OpenMP construct persists only for the duration of that construct and is private for each thread awork sharing loop persists only for the duration of one iteration of that loop a section of a work sharing sections construct persists only for the duration of that section The following code segments show examples of these rules 40 C forAIX Users Guide int El shared static void main argvc argvc is shared int i shared automatic void p malloc memory allocated by malloc is accessible by all threads
408. length Appendix B 32 bit to 64 bit Migration Considerations 343 Miscellaneous Issues e The sizeof operator will now return size_t which is an unsigned long e The length of the integer required to hold the difference between two pointers is ptrdiff_t and is a signed long type e Masks will generally lead to different results when compiled in 64 bit mode from their 32 bit mode behavior e Many include files have pointers and structures in them and their inclusion in 64 bit mode will change the size of your data section even if your program does not use structures and pointers explicitly e __int64 is a long type in 64 bit mode but will look like a long long type in 32 bit mode __int64 types can participate in promotion rules and arithmetic conversion when in 64 bit mode When in 32 bit mode these types can not participate in the usual arithmetic conversions e In 64 bit mode member values in a structure passed by value to a va_arg argument may not be accessed properly if the size of the structure is not a multiple of 8 bytes This is a known limitation of the operating system e In 64 bit extended mode zero extension from unsigned int to an unsigned long preserves the bit pattern For example zero extending an unsigned int with value OxFFFF FFFF large negative value results in an unsigned long with value 0x0000 0000 FFFF FFFF large positive value Interlanguage Calls with FortranA significant number of applications use C C
409. lent to define name Dname is equivalent to define name 1 This is the default To aid in program portability and standards compliance the AIX Version 4 OPerating System provides several header files that define macro names you can set with the D option You can find most of these header files either in the usr include directory or in the usr include sys directory See Header Files Overview in the AlX Version 4 Files Referencefor more information The configuration file uses the D option to specify the following predefined macros e POWER e AIX e _AIX32 e _IBMR2 e _ANSI_C_SOURCE 250 C for AIX User s Guide To ensure that the correct macros for your source file are defined use the D option with the appropriate macro name If your source file includes the usr include sys stat h header file you must compile with the option D_ POSIX_SOURCE to pick up the correct definitions for that file If your source file includes the usr include standards h header file ANSILC SOURCE _XOPEN_SOURCE and _POSIX_SOURCE are defined if you have not defined any of them The Uname option has a higher precedence than the Dname option Example To specify that all instances of the name COUNT be replaced by 100 in myprogram c enter xlc myprogram c DCOUNT 100 This is equivalent to having define COUNT 100 at the beginning of the source file Related Reading datalocal dataimported Option Type Default Value pragma opti
410. lets you use the character in identifiers Identifiers used by C library functions that begin with two underscores or an underscore followed by a capital letter are reserved in all contexts Although the names of system calls and library functions are not reserved words if you do not include the appropriate headers avoid using them as identifiers Duplication of a predefined name can lead to confusion for the maintainers of your code and can cause errors at link time or run time If you include a library in a program be aware of the function names in that library to avoid name duplications You should always include the appropriate headers when using standard library functions Related Reading Chapter 6 The C Language 47 Constants A constant does not change its value while the program is running The value of any constant must be in the range of representable values for its type The C language contains the following types of constants also called iterals Integer Constant Integer constants can represent decimal octal or hexadecimal values gecimea ys oomoteaat OT AL oomsteaurt Semeaceci nes comatat 1 1 L L Data Types for Integer Constants The data type of an integer constant is determined by the form value and suffix of the constant The following table lists the integer constants and shows the possible data types for each constant The smallest data type that can represent the constant value is u
411. licit Conversions page hed describes how the compiler performs conversions Usual Arithmetic ConversionsThe usual arithmetic conversions reduce the types of objects that the compiler handles when performing arithmetic operations Many compilers perform arithmetic operations only on objects having one of several data types These types are int unsigned int long unsigned long float double and long double If all operands do not have one of these types the system converts the values of the operands according to the following procedures 1 Widening values that do not have data types appropriate for arithmetic operations 2 Type balancing values in operations that have more than one operand 3 Sign balancing values in operations that have more than one operand The following sections describe the usual arithmetic conversion procedures Widening Widening expands the size of a value for example short to int by padding bits located to the left of the value with a copy of the sign bit Widening does not affect the sign of the value The following table shows the types of values that the compiler widens The compiler treats char objects as unsigned values Widening of a char yields an int that has a positive value Many compilers widen float values to double values before performing arithmetic operations Where possible C for AIX performs double precision arithmetic on float values 168 C for AIX User s Guide Type Balancing Typ
412. ll the threads in a parallel region Identifies a memory location that must be updated atomically and not be exposed to multiple simultaneous writing threads Synchronization construct identifying a point at which the compiler ensures that all threads in a parallel region have the same view of specified objects in memory Identifies a structure block of code that must be executed as a sequential loop Defines the scope of selected file scope data variables as being private to a thread but file scope visible within that thread pragma ibm critical Preprocessor Directive The critical pragma identifies a critical section of program code that must only be run by one process at a time Syntax pragma ibm critical name lt statement gt where name can be used to optionally identify the critical region Identifiers naming a critical region have external linkage 382 cC for AIX User s Guide Notes The compiler reports an error if you try to branch into or out of a critical section Some situations that will Cause an error are e A critical section that contains the return statement e Accritical section that contains goto continue or break statements that transfer program flow outside of the critical section e A goto statement outside a critical section that transfers program flow to a label defined within a critical section A thread waits at the start of a critical region identified by a given name until no othe
413. llowing the operator e Concatenation takes place before any macros in arguments are expanded e If the result of a concatenation is a valid macro name it is available for further replacement even if it appears in a context in which it would not normally be available e f more than one operator and or Prep s pera pac operator appears in the replacement list of a macro definition the order of evaluation of the operators is not defined The following examples demonstrate the use of the operator Sample Preprocessor Macro Definitions define ArgArg x y x y define ArgText x x TEXT define TextArg x TEXT x define TextText TEXT text define Jitter 1 define bug 2 define Jitterbug 3 ArgArg lady bug ladybug 378 C for AIX User s Guide ArgText con conTEXT TextArg book TEXTbook TextText TEXTtext Related Reading The operator differs from the 4 i operator only in the way that the preprocessor treats white space between the oper tor and its NER A For example the macro definition define XY x y x y does not give the same result as define XY x y x y because the gi preserves white space with the operator With the Preprocessor Macrol operator arguments are concatenated without white space The following examples demonstrate the use of the operator Sample Preprocessor Macro Definitions define wsl x y x y define ws2 x
414. located or freed object to a callback function that you provide You can then use the information however you like These heap checking functions are defined in lt umalloc h gt the regular versions are also in lt malloc h gt They are not controlled by a compiler option so you can use them in your program at any time Which Should Use Both sets of debugging functions have their benefits and drawbacks Which you choose to use depends on your program your problems and your preference The debug memory management functions provide detailed information about all allocation requests you make with them in your program You don t need to change any code to use the debug versions you need only specify the qheapdebug compiler option However because only calls that have been mapped to debug versions provide any information you may have to rebuild many or all of your program s modules which can be time consuming On the other hand the heap checking functions perform more general checks on the heap at specific points in your program You have greater control over where the checks the occur The heap checking functions also provide compatibility with other compilers that offer these functions You only have to rebuild the modules that contain the heap checking calls However you have to change your source code to include these calls which you will probably want to remove in your final code Also the heap checking functions only tell you i
415. lon An integer describing the current source line number The value of _ LINE __ changes during compilation as the compiler processes subsequent lines of your source program It can be set with the line directive A character string literal conatining the name of the source file The value of _ FILE _ changes as the compiler processes include files that are part of your source program It can be set with the line directive A character string literal containg the date when the source file was compiled The value of _ DATE__ changes as the compiler processes any include files that are part of your source program The date is in the form Mmm dd yyyy where Mmm Represents the month in an abbreviated form Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov or Dec dd Represents the day of the month If the day is less than 10 the first d is a blank character Represents the year The integer 1 one indicates that the C compiler conforms to the ANSI standard Note This macro is undefined if the language level is set to anything other than ANSI A character string literal containing the time when the source file was compiled The value of _ TIME _ changes as the compiler processes any include files that are part of your source program The time is in the form hh mm ss where hh Represents the hour dd Represents the minutes yyyy Represents the seconds The time is always set to the system time Appen
416. lt is to compile and link edit C source files to produce an executable file Related Reading Option Type Default Value pragma options e Syntax p Purpose Sets up the object files produced by the compiler for profiling If the qtbtable option is not set the p option will generate full traceback tables Example To compile myprogram c so that it can be used with the AIX prof command enter xlc myprogram c p Note When compiling and linking in separate steps the p option must be specified in both steps Related Reading pascal Option Type Default Value pragma options fp aoption oases Syntax qpascal qnopascal 308 c for AIX User s Guide Purpose Ignores the word pascal in type specifiers and function declarations Notes This option can be used to improve compatibility of C for AIX programs on some other systems Related Reading pdf1 pdf2 Option Type Default Value pragma options qoption nopdf1 nopdf2 Syntax qpdf1 qpdf2 qnopdf1 qnopdf2 Purpose Tunes optimizations through Profile Directed Feedback PDF where results from one or more sample program executions are used to improve optimization near conditional branches and in frequently executed code sections Notes To use PDF 1 Compile some or all of the source files in a program with the qpdf1 option main must be compiled The ge 286pdf option is required during the link step the O3 option is recommended
417. lue pragma options Syntax qhssngl qnohssngl HSSNGL NOHSSNGL Purpose Specifies that single precision expressions are rounded only when the results are stored into float memory locations nohssngl specifies that single precision expressions are rounded after expressione valuation Using hssngl can improve run time performance Notes This option is obsolete Use qfloat hssngl in your new applications Option Type Default Value pragma options e Syntax Idirectory Purpose Specifies an additional search path if the file name in the include directive is not specified using its absolute path name Notes The value for directory must be a valid path name for example u golnaz or tmp or subdir The compiler appends a slash to the directory and then concatenates it with the file name before doing the search The path directory is the one that the compiler searches first for include files whose names do not start with a slash If directory is not specified the default is to search the standard directories The normal search order is 1 Search the directory where the current source file resides 2 Search the directory or directories specified with the I directory option 3 Search the standard include directory usr include If the I directory option is specified both in the configuration file and on the command line the paths specified in the configuration file are searched first When all specified
418. lues of the predefined macros _ LINE _ _FILE_ __TIME_ and _ DATE __ and print a message indicating the program s conformance to ANSI ISO standards based on _ STDC _ x xx This example illustrates some predefined macros sk pragma langlvl ANSI include lt stdio h gt if STDC define CONFORM conforms else define CONFORM does not conform endif int main void printf Line d of file s has been executed n _ LINE _ FILE printf This file was compiled at s on s n _ TIME _ DATE printf This program s to ANSI ISO standard C n CONFORM 362 C for AIX User s Guide Example 2 The following program uses the _ FUNCTION__ macro to determine the name of the program function currently in effect x xx This example illustrates the _ FUNCTION __ predefined macro xx in a C program include lt stdio h gt int foo int main int argc char argv int k 1 printf In function s n FUNCTION foo k int foo int i printf In function s n FUNCTION The output of this example is In function main In function foo Related Reading pragma Preprocessor Directives A pragma is an implementation defined instruction to the compiler It has the general form ee t Sei eee eres where character_sequence is a series of characters giving a specific compiler instruction and arguments if any The character_sequence on a pragma is not subject to macro subst
419. ma harfie fftename This pragma must appear before the first include directive and either the qgenpcomp or qusepcomp compiler options must also be specified If a file name is specified by both a qgenpcomp or qusepcomp compiler option and a pragma hdrfile entry the name specified by the pragma takes precedence If the name specified is a directory the compiler searches for or generates a file with the default name in that directory In order to maximize the reuse of precompiled headers use pragma hdrfile in combination with pragma hdrstop to manually limit the initial sequence of include directives Using precompiled header files can decrease compile time Using precompiled headers will not improve compile time performance in most applications without some organization of the headers included by each source file Some examples of pragma hdrfile directives are BRK RE KK EK RRR RRR RRR ER KER ERK ERK ERR ERR ERK ERK EK KEKE RRR KEKE RR k Kk k ERK kK kK K KK KK k Kk In the following example the headers hl h and h2 h are precompiled and the precompiled output is written to the file fred pch provided the qgenpcomp compiler option is specified If qgenpcomp dave pch is specified the precompiled output will still be written to fred pch since the name specified in the pragma takes precedence To use the precompiled output in fred pch when compiling specify the qusepcomp compiler option 368 C for AIX User s
420. may occur Represent as double if the long cannot be represented exactly some loss of precision may occur Represent as double if the long long cannot be represented exactly some loss of precision may occur ee Sign extend to int and Sign extend to int and Sign extend to int and convert int to float convert int to double convert int to long double Sign extend to int and Sign extend to int and Sign extend to int and convert int to float convert int to double convert int to long double Represent as long double if the int cannot be represented exactly some loss of precision may occur Represent as long double if the long cannot be represented exactly some loss of precision may occur Represent as long double if the long long cannot be represented exactly some loss of precision may occur Sign extend to int and Sign extend to int and Sign extend to int and convert int to float convert int to double convert int to long double Sign extend to int and Sign extend to int and Sign extend to int and convert int to float convert int to double convert int to long double Represent as long double if the int cannot be represented exactly some loss of precision may occur Represent as long double if the long cannot be represented exactly some loss of precision may occur Represent as long double if the long long cannot be represented exactly some loss of precision may occur Convert to double Convert
421. me In the example the union people contains either age birthday or weight but never more than one of these The printf statement in the following example does not give the correct result because people age replaces the value assigned to people birthday in the first line 1 people birthday 03 06 56 2 people age 38 3 printf s n people birthday Defining a Union Variable A union variable definition contains an optional storage class keyword the union keyword a union tag and a declarator The union tag indicates the data type of the union variable Chapter 6 The C Language 103 The type specifier contains the keyword union followed by the name of the union type You must declare the union data type before you can define a union having that type You can define a union data type and a union of that type in the same statement by placing the variable declarator after the data type definition The declarator is an identifier possibly with the volatile or const qualifier The initializer must be a constant expression if the union has static storage duration or if you are compiling your source code in ansi mode If the union has auto storage duration it can be initialized using the equal sign followed by any expression that returns a compatible union value You can only initialize the first member of a union The following example shows how you would initialize the first union member birthday of the union variable peopl
422. mem s ize Purpose Limits the amount of memory used for local tables of specific memory intensive optimizations to size kilobytes If that memory is insufficient for a particular optimization the scope of the optimization is reduced Notes e A size value of 1 permits each optimization to take as much memory as it needs without checking for limits Depending on the source file being compiled the size of subprograms in the source the machine configuration and the workload on the system this might exceed available system resources e The limit set by maxmem is the amount of memory for specific optimizations and not for the compiler as a whole Tables required during the entire compilation process are not affected by or included in this limit e Setting a large limit has no negative effect on the compilation of source files when the compiler needs less memory e Limiting the scope of optimization does not necessarily mean that the resulting program will be slower only that the compiler may finish before finding all opportunities to increase performance e Increasing the limit does not necessarily mean that the resulting program will be faster only that the compiler is better able to find opportunities to increase performance if they exist e The option O3 implies qmaxmem 1 The default is qmaxmem 2048 which specifies a default memory size Depending on the source file being compiled the size of the subprograms in the source the m
423. ment After macro replacement the resulting character sequence must consist of a decimal constant optionally followed by a file name enclosed in double quotation marks Note In extended mode the keyword line is optional The directive line 300 is equivalent to 300 The keyword line is required in ansi mode Related Reading undef Preprocessor Directive A preprocessor undef directive causes the preprocessor to end the scope of a preprocessor definition Fp t undef identifier 4 If the identifier is not currently defined as a macro undef is ignored Macros can also be undefined with the U compiler option Example of Usage The following directives define BUFFER and SQR define BUFFER 512 define SQR x x x The following directives nullify these definitions undef BUFFER undef SQR Any occurrences of the identifiers BUFFER and SQR that follow these undef directives are not replaced with any replacement tokens Once the definition of a macro has been removed by an undef directive the identifier can be used in a new define directive Related Reading 358 C for AIX User s Guide Predefined Preprocessor Macros C for AIX includes two groups of predefined preproccessor macros The first group contains macros defined by the ANSI standard for the C programming language The second group contains macros provided by C for AIX ANSI Standard Predefined Preprocessor Macros Rome Reseript
424. ments Most options specified in the configuration file override the default settings of the option Similarly most options specified in the configuration file are in turn overridden by options set in the source file and on the Tailoring a Configuration FileThe default configuration file is etc vac cfg You can copy this file and make changes to the copy to support specific compilation requirements or to support other C compilation environments To specify a configuration file other than the default you use the F option For example to make qnoro the default for the xlc compiler invocation command add qnoro to the xlc stanza in your copied version of the configuration file You can link the compiler invocation command to several different names The name you specify when you invoke the compiler determines which stanza of the configuration file the compiler uses You can add other stanzas to your copy of the configuration file to customize your own compilation environment You can use the F option with the compiler invocation command to make links to select additional stanzas or to specify a stanza or another configuration file For example xlc myfile c Fmyconfig SPECIAL would compile myfile c using the SPECIAL stanza in a myconfig cfg configuration file that you had created Configuration File Attributes A stanza in the configuration file can contain the following attributes as Path name to be used for the assembler The defaul
425. mount of swapping required e In multithread applications only one thread can access the heap at a time to ensure memory is safely allocated and freed For example say thread 1 is allocating memory and thread 2 has a call to free Thread 2 must wait until thread 1 has finished its allocation before it can access the heap Again this can slow down performance especially if your program does a lot of memory operations If you create a separate heap for each thread you can allocate from them concurrently eliminating both the waiting period and the overhead required to serialize access to the heap e With a single heap you must explicitly free each block that you allocate If you have a linked list that allocates memory for each node you have to traverse the entire list and free each block individually which can take some time If you create a separate heap for that linked list you can destroy it with a single call and free all the memory at once e When you have only one heap all components share it including the C for AIX runtime library vendor libraries and your own code If one component corrupts the heap another component might fail You may have trouble discovering the cause of the problem and where the heap was damaged 182 C for AIX Users Guide With multiple heaps you can create a separate heap for each component so if one damages the heap for example by using a freed pointer the others can continue unaffected You also k
426. mpiler listing flag See Adds the prefix specified by the B option to designated programs qopt tabsize 8 Changes the length of tabs as perceived by the compiler qopt full Sets traceback table characteristics qopt See Indicates to the compiler hage 3311 that the program will run in a multi threaded environment qopt See for which the executable program is optimized flag Undefines a specified identifier defined by the compiler or by the D option unroll on page 333 qopt unroll 4 Unrolls inner loops in the program by a specified factor on page 334 qopt noupconv Preserves the unsigned specification when performing integral promotions Appendix A Compiler Options 225 Specifies the architecture usepncomp on page 335 nousepcomp Use precompiled header files for any files that have not changed since the precompiled header was created Instructs the compiler to report information on the progress of the compilation Passes the listed words to a designated compiler program Requests that warning messages be suppressed nowarn64 Enables warning of possible long to integer data truncations noxcall Generates code to static routines within a compilation unit as if they were external calls noxref Produces a compiler listing that includes a cross reference listing of all identifiers Specifies the compile time rounding mode of constant floating point expressions Lists of Co
427. mpiler Options by Functional Groupings Options that Specify Compiler Characteristics Specify a different configuration file or stanza Specify a search path l on page 272 226 for AIX User s Guide Specify if char variables are treated as signed or unsigned Produce only line number and source file name information for dbx Produce debug information for dbx Generates symbols for use by tools based on the Dynamic Probe Class Library DPCL Enable debug versions of memory management functions Speo full path information when you use with dbx Generate and set the charcateristics of the traceback Appendix A Compiler Options 227 Options that Specify Preprocessor Options Perform syntax checking but do not generate an object file Compile but not link Create a dynamic library object file Id command only pag Produce compiler listings Suppress messages pag fw on page 337 Halt the compiler output if errors of specified severity or halt on page 26d greater are encountered Halt the compiler output if num errors of specified or greater severity are encountered Produce information messages Report the time taken for compilation ohsinfo on page 312 Report status information as the compilation proceeds O Trace the compilation 228 C for AIX User s Guide Related Reading Specify the architecture on which the executable program will be run Use the linkage editor to create a dynam
428. mplementation Dependencies Overview 451 The 2 byte alignment rules remain unchanged All identifiers and aggregates are aligned on a 16 bit boundary For bind time type checking a long double has type r16 There are three floating types float double and long double The range of values of each type is a subrange of the values of the next type in the list When the compiler converts a value of floating type to integral type the fractional part is discarded If the value of the integral part is too large to be represented by an integral type the value is converted to the maximum value of an integral type When a long double is demoted to double or float if the value being converted is in the range of values that can be represented but cannot be represented exactly the result is either the nearest higher or nearest lower value depending on the IEEE rounding mode Related Reading Implementation Dependency Arrays and Pointers F 3 7 The type of the integer required to hold the maximum size of an array the type of the sizeof operator size_t is unsigned long 3 3 3 4 and 4 1 1 For a pointer to be converted to an integral type the size of integer required is 32 or 64 bits 3 3 4 The type of the integer required to hold the difference between two pointers to elements of the same array ptrdiff_t is long 3 3 6 and 4 1 1 When a pointer is cast to an integer or an integer is cast to a pointer the bit patterns are prese
429. mpted by the compiler when the O3 option is specified Chapter 7 Writing C Programs 201 Related Reading Using Inlined Components By default the compiler inlines certain library functions meaning that it replaces the function call with the actual code for the function at the point where the call was made These library functions are called intrinsic or built in functions You can also request that the compiler inline the code for your own functions There are benefits and drawbacks of and restrictions on inlining user code There are two ways to inline user code 1 Use the C for AIX _inline Inline and __ inline keywords to specify which functions you want to have inlined You must specify the Q or qinline options to turn inlining on 2 Use the Q or qinline option with a value parameter to automatically inline functions smaller than the value specified You should use inlining only for very small functions See Q or qinline for more information about the inlining option Note Requesting that a function be inlined makes it a candidate for inlining but does not necessarily mean that the function will be inlined In all cases the compiler ultimately decides whether a function is inlined Benefits of Inlining Inlining user code eliminates the overhead of the function call and linkage and also exposes the function s code to the optimizer resulting in faster code performance Inlining produces the best results when
430. n Related Reading Converting Files Containing Multibyte Data to New Code Pages If you have installed new code pages on your system you must use the AIX iconv migration utility to convert files containing multibyte data to use new code pages This command converts files containing multibyte data from the IBM 932 code set to the IBM euc code set The iconv command is described in the AlX Version 4 Commands Reference Using the NLS code set converters with the iconv command is described in Converters Overview for Programming in the AIX Version 4 General Programming Concepts Related Reading Where Multibyte Characters Are Supported In the examples that follow multibyte_char represents any string of one or more multibyte characters String Literals and Character Constants Multibyte characters are supported in string literals and character constants Strings containing multibyte characters are treated in essentially the same way as strings without multibyte characters Multibyte characters can appear in several contexts e Preprocessor directives e Macro definitions e The and operators e The definition of the macro name in the D compiler option Wide character strings can be manipulated the same way as single byte character strings The system provides equivalent wide character and single byte string functions Copyright IBM Corp 1995 1999 469 The default storage type for all string literals is read only T
431. n qnostrict induction Purpose Setting qstrict_induction disables loop induction variable optimizations that have the potential to alter the semantics of your program Such optimizations can change the result of a program if truncation or sign extension of a loop induction variable should occur as a result of variable overflow or wrap around Notes This option affects only loops which have an induction loop counter variable declared as a different size than a register The most probable incidence of such a situation will likely involve using 32 bit loop counters int or unsigned int when compiling in 64 bit mode Unless you intend such variables to overflow or wrap around use qnostrict_induction Using qstrict_induction can cause considerable performance degradation However the option may be useful for debugging a program sensitive to variable overflow or wrap around Default e qstrict_induction with optimization level 0 or when using c89 compiler invocation mode e qnostrict_induction otherwise Related Reading syntaxonly Option Type Default Value pragma options e a Syntax qSYNTAXonly Purpose Causes the compiler to perform syntax checking without generating an object file Notes The P E and C options override the qsyntaxonly option which in turn overrides the c and o options The qsyntaxonly option suppresses only the generation of an object file All other files listings precompiled header file
432. n Parameter promotions are performed and no type checking is done You cannot declare a function as a structure or union member A function cannot have a return type of function array or any type having the volatile or const qualifier However it can return a pointer to an object with a volatile or const type You cannot define an array of functions You can however define an array of pointers to functions Function Declarator The function declarator shown in the function definition syntax diagram names the function and lists the function parameters It contains an identifier that names the function and a list of the function parameters You should always use prototype function declarators because of the parameter checking that can be performed The detailed syntax structure for the function declarator is ee d arraio Te _ _ 4 ant tier 140 C for AIX Users Guide where parameter_declaration_list siorage_class_specmer Tyoe_specmer Yee QUEME abstract deckretor shetectcecketor dect abstract decletor COE es ressigy i 1 evereter dec Bahon iSt abstract_declarator Prototype Function Declarators Each parameter should be declared within the function declarator Any calls to the function must pass the same number of arguments as there are parameters in the declaration Nonprototype Function Declarators Each parameter should be declared in a parameter declaration list following th
433. n Parallelized Loops Shared and Private Variables in a Parallel Environment Using Pragmas to Control Parallel Processing Copyright IBM Corp 1995 1999 XV XV XVII XVII XVii xviii ooh FRA WWW W Chapter 6 The C Language Lexical Elements of C Tokens Comments Identifiers Constants Identifier Behavior in Your Program Scope of Identifier Visibility a Program Linkage Between Identifiers Storage Duration Name Spaces Preprocessor Directives Preprocessing Operations Preprocessor Macros Conditional Compilation Directives Declarations Overview Block Scope Data Declarations Initialization Storage l File Scope Data Declarations Declarators Storage Class Specifiers Initializers Type Specifiers Expressions and Operators Operator Precedence and Associativity Operands lvalues Types of Expressions Constant Expressions Function Calls Implicit Type Conversions Integral Promotions Standard Type Conversions Arithmetic Conversions Functions Calling Functions and Passing Arguments C Language Levels Basic Data Types char float double int long short enum void Derived Data Types Arrays Pointers struct Structures union Unions Incomplete Types auto extern register static typedef Data Type Qualifiers VIC for AIX User s Guide Expression Operators Operator Precedence and Associativit
434. n a string constant are retained To continue a string on the next line use the line continuation sequence symbol immediately followed by a new line character A carriage return must immediately follow the backslash In the following example the string literal second causes a compile time error char first This string continues onto the next line where it ends compiles successfully char second The comment makes the continuation symbol invisible to the compiler compilation error x Another way to continue a string is to have two or more consecutive strings Adjacent string literals are concatenated to produce a single string You cannot concatenate a wide string constant with a character string constant For example hello there is equivalent to hello there hello L there is not valid hello there is equivalent to hellothere Characters in concatenated strings remain distinct For example the strings xab and 3 are concatenated to form xab3 However the characters xab and 3 remain distinct and are not merged to form the hexadecimal character xab3 Following any concatenation 0 of type char is appended at the end of each string C programs find the end of a string by scanning for this value For a wide character string literal 0 of type wcehar_t is appended For example char first Hello stored as Hello 0 x char
435. n atan2 the bessel functions y0 y1 yn fmod gamma log logi0 pow sq Related Reading Arithmetic Conversions for extended Level C This page describes the rules for arithmetic conversions that the compiler adheres to when the language specified is extended Described are Usual Unary Conversions page h62 e Usual Arithmetic Conversions page hesh Widening page hes Type Balancing page h68 Sign Balancing page 169 e Assignment Conversions Table page hed e Explicit Conversions page keo Reduction Conversions page Expansion Conversions page 7d Pointer Conversions page 7d void Conversions page HZ volatile Conversions page hzo Usual Unary ConversionsThe usual unary conversions reduce the types of values that the compiler must handle The compiler uses the usual unary conversions on e The operands of the unary operators and Chapter 6 The C Language 167 e The operands of the binary operators lt and gt e The arguments in a function call before the function is called and if a function prototype is not available The following table lists the types of values that the usual unary conversions affect Type of Value Note The compiler performs the usual unary conversion of float to double on arguments in function calls only When a float object appears as an operand of lt or gt the compiler does not perform a usual unary conversion Exp
436. n be specified on an omp parallel directive Specifying default shared is equivalent to stating each variable in a shared isf clause Specifying default none requires that each data variable visible to the parallelized statement block must be explcitly listed in a data scope clause with the exception of those variables that are e const qualified e specified in an enclosed data scope attribute clause or e used as a loop control variable referenced only by a corresponding omp for or omp parallel for directive 388 C for AIX User s Guide reduction operator Performs a reduction on all scalar variables in ist using the specified operator Reduction list variables in list are separated by commas A private copy of each variable in list is created for each thread At the end of the statement block the final values of all private copies of the reduction variable are combined in a manner appropriate to the operator and the result is placed back into the original value of the shared reduction variable Variables specified in the reduction clause e must be of a type appropriate to the operator e must be shared in the enclosing context e must not be const qualified e must not have pointer type Notes Loop iterations must be independent before the loop can be parallelized An implied barrier exists at the end of a parallelized statement block Nested parallel regions are always serialized Related Reading pragm
437. n identifier must follow the ifndef keyword The following example defines MAX_LEN to be 50 if EXTENDED is not defined for the preprocessor Otherwise MAX_LEN is defined to be 75 ifndef EXTENDED define MAX_LEN 50 else define MAX LEN 75 endif Related Reading Examples of Conditional Preprocessor Directives Example 1 The following example shows how you can nest preprocessor conditional compilation directives if defined TARGET1 define SIZEOF INT 16 ifdef PHASE2 define MAX PHASE 2 else define MAX PHASE 8 endif elif defined TARGETZ define SIZEOF INT 32 define MAX PHASE 16 else define SIZEOF INT 32 define MAX PHASE 32 fendif A EHHH H H Appendix D Preprocessor Directives and Related Information 355 Example 2 The following program contains preprocessor conditional compilation directives x xx This example contains preprocessor xx conditional compilation directives include lt stdio h gt int main void static int array 1 2 3 4 5 Int 713 for i 0 i lt 4 i array i 2 if TEST gt 1 printf i d n i printf arrayli d n arrayl i endif return 0 Related Reading include Preprocessor Directive A preprocessor include directive causes the preprocessor to replace the directive with the contents of the specified file ee include He aa Fa L te neme idenihers The preprocessor resolves macros contained in a inclu
438. n speed and runtime performance The optimizations may change from one product release to the next If you need a specific level of optimization specify the appropriate numeric value This setting implies qnostrict_induction unless qstrict_induction is explicitly specified O2 qOPTimize 2 Same as O 302 cC for AIX User s Guide 03 qOPTimize 3 Performs additional optimizations that are memory intensive compile time intensive or both These optimizations are performed in addition to those performed with only the O option specified They are recommended when the desire for runtime improvement outweighs the concern for minimizing compilation resources This level is the compiler s highest and most aggressive level of optimization O3 performs optimizations that have the potential to slightly alter the semantics of your program It also applies the O2 level of optimization with unbounded time and memory The compiler guards against these optimizations at O2 You can use the qstrict option with O3 to turn off the aggressive optimizations that might change the semantics of a program qstrict combined with O3 invokes all the optimizations performed at O2 as well as further loop optimizations Note that the qstrict compiler option must appear after the O3 option otherwise it is ignored Appendix A Compiler Options 303 The aggressive optimizations performed when you specify O3 are i 304 C for AIX User s Guide
439. n void double f 3 0 printf absolute number 1f n absolute f double absolute double number if number lt 0 0 number number return number The following example defines the function absolute with the return type void Within the function main absolute is declared with the return type void include lt stdio h gt int main void void absolute float float f 8 7 absolute f void absolute float number if number lt 0 0 number number printf absolute number f n number Related Reading Function Definitions ction decla fetor extern toe seeqnier static r biock statement hed A function definition either prototype or nonprototype contains the following e An optional storage class specifier extern or static which determines the scope of the function If a storage class specifier is not given the function has external linkage e An optional type specifier which determines the type of value that the function returns If a type specifier is not given the function has type int Chapter 6 The C Language 139 e A function declarator which provides the function with a name can further describe the type of the value that the function returns and can list any parameters that the function expects and their types The parameters that the function is expecting are enclosed in parentheses e A block statement which contains data definitions and code A non
440. n void Function definition for main function double z Local variable definitions x double w z cos x cos is declared in math h as double cos double arg x w cos y printf cosine of x is f n z Print cosine of x printf cosine of y is f n w Print cosine of y return 0 The program above defines main and declares a reference to the function cos The program defines the global variables x and y initializes them and declares two local variables z and w Related Reading Example of a C Program Comprised of Two Source Files The following example shows a C program source comprised of two source files The main and max functions are in separate files The program logic starts with the main function Example Program with Two Source Files KEK Kk k k k k RE KR RRR KEKE RRR EKER KERR EKER KEKE KERR RRR EKER kk EKER ERE kk Source file 1 main function KK KKK KK KK ERK KEK RRR RK kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkx define ONE 1 define TWO 2 define THREE 3 extern int max int int Function declaration int main int argc char argv Function definition int u W X Y Z 5 2 max u ONE max w TWO max x THREE max y z return Z NX X ZENOC II 176 C for AIX Users Guide BRK RR KK ERK EK RRR RRR ERR kk Kk k KERR k AEE RRR k k kk kk kkk k kkk Kk kk kK k Source file 2 max function KKK KK KK kkk kkk kkkkkkkkkkkkkkkkkkkk
441. n with two underscores _ in the usr vac include string h header file Indicates that the target hardware is an Intel processor Indicates that the target hardware is a RISC 6000 processor A hexadecimal constant containing the version number of the compiler The version is in the form OxVVRR where VV Represents the compiler version number RR Represents the compiler release number For C for AIX Version 5 Release 0 the macro has the value 0x0500 Appendix D Preprocessor Directives and Related Information 361 Meme eee ACIZI Instructs the compiler to generate substitute code for calls to some new string and math functions The functions handled this way are defined as replacement text for macros that begin with two underscores __ in the following header files e usr vac include string h e usr vac include math h e usr vac include stdlib h e usr vac include stream h Notes 1 The value of all C for AIX macros are defined when the corresponding pragma directive or compiler option is used 2 Except for MATH _STR_ and _XLC121__ macros predefined macro names cannot be the subject of a define or undefine preprocessor directive The preprocessor ignores any redefined macros and issues an error message 3 You cannot use the U option to undefine a predefinedmacro name Related Reading Examples of Predefined Macros in a Program Example 1 The following printf statements display the va
442. nans specifies that this conversion need not be detected qfloat nans is required for full compliance to the IEEE 754 standard The hsflt option overrides the nans option When used with the qflttrap or qflttrap invalid option the compiler detects invalid operation exceptions in comparison operations that occur when one of the operands is a signalling NaN The qfloat nans option replaces the obsolete qfloat spnans option and the qspnans option Use qfloat nans in your new applications Specifies that the result of each single precision float operation is to be rounded to single precision qfloat norndsngl specifies that rounding to single precision happens only after full expressions have been evaluated Using this option may sacrifice speed for consistency with results from similar calculations on other types of computers The hsflt option overrides the rndsngl option The qfloat rndsngl option replaces the obsolete qrndsnglI option Use qfloat rndsngl in your new applications Prevents floating point optimizations that are incompatible with runtime rounding to plus and minus infinity modes Informs the compiler that the floating point rounding mode may change at run time or that the floating point rounding mode is not round to nearest at run time qfloat rrm must be specified if the Floating Point Status and Control register is changed at run time as well as for initializing exception trapping The qfloat rrm option r
443. nction searches through an array of integers to determine if a match exists for the variable number If a match exists the function match returns the value of i If a match does not exist the function match returns the value 1 negative one int match int number int array int n int i for i 0 i lt n i if number array i return i return 1 154 C for AIX User s Guide Related Reading switch A switch statement lets you transfer control to different statements within the switch body depending on the value of the switch expression The switch expression must evaluate to an integral value The body of the switch statement contains case clauses that consist of e A case label e An optional default label e A case expression e A list of statements If the value of the switch expression equals the value of one of the case expressions the statements following that case expression are processed If not the default label statements if any are processed Pe switeh expression wich body p lt The switch body is enclosed in braces and can contain definitions declarations case clauses and a default clause Each case clause and default clause can contain statements Pr tyoee_detintion ie scope dete deckretion block _ scope det dec raion L der case Bun clause Note An initializer within a type_definition file_scope_data_declaration or block_scope_data
444. nd xlc qmakedep conversion c filter c lib libm a produces two output files conversion u and filter u and an executable file as well No u file is created for the library If the current directory is not writable no u file is created If you specify ofile_name along with qmakedep the u file is placed in the directory implied by ofile_name For example for the following invocation xlc qmakedep c t c o tmp t o places the u output file in tmp t u Format of the Output File The output file contains a line for the input file and an entry for each include file It has the general form file name o file name cfile name o include file name Include files are listed according to the search order rules for the include preprocessor directive described in Directo j ive Path Names on paqe the include file is not found it is not added to the u file 298 C for AIX User s Guide Files with no include statements produce output files containing one line that lists only the input file name Related Reading maxerr Option Type Default Value pragma options fp aoptin oman Syntax qmaxerr num sev_level qnomaxerr Purpose Instructs the compiler to halt compilation when num errors of severity sev_ evel or higher is reached Notes num must be an integer sev_ eve must be one of the following sev_level Description i Informational Warning Error Severe error no z If no value is spe
445. ned at block scope printf d nzd n i j Prints 2 3 l int i 0 i is redefined in a nested block previous definitions of i are hidden printf d nzd n i j Prints 0 3 printf d n i Prints 2 x i printf d n i Prints 1 return 0 i RELATED CONCEPTS 56 C for AIX User s Guide RELATED TASKS Storage Duration Storage duration determines how long storage for an object exists An object has either static storage duration or automatic storage duration depending on its declaration Descriptions of each follow Static storage Is allocated at initialization and remains available until the program ends Objects have static storage duration if they e Have file scope e Have external or internal linkage OR e Contain the static storage class specifier Automatic storage Is allocated and removed according to the scope of the identifier Objects have automatic storage duration if they are e Parameters in a function definition e Declared at block scope and do not have any storage class specifier or e Declared at block scope and have the register or auto storage class specifier For example storage for an object declared at block scope is allocated when the identifier is declared and removed when the closing brace is reached Note Objects can also have heap storage duration Heap objects are created at runtime and storage is allocated for them by calling
446. nerates extra instructions to detect and trap floating point exceptions Specifies that constant floating point expressions are to be evaluated at compile time Specifies what path information is stored for files when you use the g option Linkage editor Id command option only Used to generate a dynamic libary file _ Generates debugging information used by the debugger Generates a precompiled version of any header file for which the original source is used nogenpcomp nogenproto Produces ANSI prototypes from K amp R function definitions halt s Instructs the compiler to stop after the compilation phase when it encounters errors of specified severity or greater Enables debug versions of memory management functions noheapdebug nohsflt Speeds up calculations by removing range checking on single precision float results and on conversions from floating point to integer nohssngl Specifies that single precision expressions are rounded only when the results are stored into float memory locations Specifies an additional search path if the file name in the include directive is not specified using its absolute path name noidirfirst Specifies the search order for files included with the include file_ name directive noignerrno Allows the compiler to perform optimizations that assume errno is not modified by system calls Instructs the compiler to ignore cert
447. ng any one of the listing related options to the invocation command produces a compiler listing unless you have specified the qnoprint option The file containing this listing is placed in your current directory and has the same file name with an Ist extension as the source file from which it was produced Target File Output files associated with the M option have an usuffix for example conversion u The file contains targets suitable for inclusion in a description file for the AIX make command A u file is created for every input file with a c or i suffix u files are not created for any other files unless you use the option so other file suffixes are treated as c files Related Reading Invoking the Compiler All forms of the C for AIX compiler are invoked using the following syntax where invocation can be replaced with any valid C for AIX compiler mode invocation command gt invocation ____________________ command line options input files 8 C for AIX User s Guide The parameters of the compiler invocation command can be the names of input files compiler options and linkage editor options Compiler options perform a wide variety of functions such as setting compiler characteristics describing the object code and compiler output to be produced and performing some preprocessor functions To compile without link editing use the c compiler option The c option stops the compiler after compilation is
448. ng long int type Allowed in extended mode but not in ansi mode e Character data types char unsigned char or signed char In ansi mode the C compiler distinguishes between the three character types in extended mode the C compiler does not distinguish between char and unsigned char e Macro redefinition ansi level C requires that a macro be undefined before it can be defined again in a define directive extended level C allows macros to be redefined without first being undefined An informational message is issued that states that the second definition is used e dollar sign character in identifiers In extended mode only the compiler allows the dollar sign character to be used in identifier names to facilitate calls between different languages The dollar sign is not a valid character for identifiers in ansi mode e Macro concatenation using Allowed by extended but not by ansi Conflicts Between extended C and RT C Ideally extended mode should handle all RT C source code without conflict Certain obsolete RT C definitions do conflict with ANSI ISO C For these extended mode follows ANSI ISO C and conflicts with RT C extended level C does not support the following RT C definitions e asm and fortran keywords e External data with file scope even though declared or defined at block scope e Array initialization without braces e The last member of a structure definition not terminated by a semicolon e
449. nging the Default Heap Used ir ina Program 117 117 118 120 124 131 133 136 137 138 138 139 144 145 145 147 148 149 149 s 151 152 153 154 155 158 158 s159 159 160 161 s 161 162 162 164 164 2 167 167 170 173 174 174 174 179 176 177 178 178 178 178 179 179 182 183 Contents 183 185 Vil Creating and Using a Fixed Size Heap Creating and Using an Expandable Expanding Your Heap lt 2 Shrinking Your Heap Example of Creating and Using a User Heap Example of Creating and Using a Shared Memory User Heap Debugging Programs with Heap Memory Writing Optimized cial Source Code Variables ena Pointers Functions e Function Arguments Expressions Critical Loops Conversions Arithmetic Constructions Using Inlined Components Chapter 8 Using C for AIX with Other i Aage Interlanguage Calling Conventions Corresponding Data Types rar Special Treatment of Character and Aggregate Data l Using the Subroutine Linkage Conventions in Interlanguage Calls Interlanguage Calls Parameter Passing Interlanguage Calls Call by Reference Parameters 1 Interlanguage Calls Call by Value Parameters Interlanguage Calls Rules for Passing Parameters by Value Interlanguage Calls Pointers to Functions Interlanguage Calls Function Return Values Inter
450. nit of storage Appendix O Glossary 495 P pad To fill unused positions in a field with dummy data usually zeros ones or blanks parameter declaration A description of a value that a function receives A parameter declaration determines the storage class and the data type of the value pointer A variable that holds the address of a data object or function preprocessor A program that examines the source program for preprocessor statements that are then interpreted resulting in the alteration of the source program preprocessor directive A statement that begins with the pound sign and contains instructions that the preprocessor interprets primary expression Literals names and names qualified by the scope resolution operator prototype See k94 R register A storage area commonly associated with fast access storage capable of storing a specified amount of data such as a bit or an address register variable A variable defined with the register storage class specifier Register variables have automatic storage S scalar An arithmetic object or a pointer or a reference to an object of any type scope That part of a source program in which a variable is visible single byte character set A set of characters in which each character is represented by 1 byte of storage single precision Pertaining to the use of one computer word to represent a number in accordance with the required precision source
451. nize and properly handle most reduction operations in a loop during both automatic and explicit parallelization In particular it can handle reduction statements that have either of the following forms var var op expr var assign op expr where Is an identifier designating an automatic or register variable that does not have its address taken and is not referenced anywhere else in the loop including all loops that are nested For example in the following code only S in the nested loop is recognized as a reduction int i j S 0 pragma ibm parallel loop for i 0 i lt N i S S i pragma ibm parallel loop for j 0 j lt My j S25 1 var Is one of the following operators amp Is one of the following operators fae ae Se fe 2 op assign_op Chapter 5 Program Parallelization 39 expr Is any valid expression Recognized reductions are listed by the qinfo reduction option When using IBM directives use critical sections to synchronize access to all reduction variables not recognized by the compiler OpenMP directives provide you with mechanisms to specify reduction variables explictily Related Reading Li L A T iJ Th AN A r OO Or DOAdOe Shared and Private Variables in a Parallel Environment Variables can have either shared or private context in a parallel environment e Variables in shared context are visible to all threads running in associated paral
452. nment Variables OMP_ NUM THREADS num OMP_NESTED TRUE FALSE num represents the number of parallel threads requested which is usually equivalent to the number of processors available on the system This number can be overridden during program execution by calling the omp_set_num_threads runtime library function Some applications cannot use more threads than the maximum number of processors available Other applications can experience significant performance improvements if they use more threads than there are processors This option gives you full control over the number of user threads used to run your program The default value for num is the number of processors available on the system This environment variable enables or disables nested parallelism The setting of this environment variable can be overrridden by calling the omp_set_nested runtime library function If nested parallelism is disabled nested parallel regions are serialized and run in the current thread In the current implementation nested parallel regions are always serialized As a result OMP_SET NESTED does not have any effect and omp_get_nested always returns O If qsmp nested_par option is on only in non strict OMP mode nested parallel regions may employ additional threads as available However no new team will be created to run nested parallel regions The default value for OMP_NESTED is FALSE Dynamic Profiling Environment Variable OMP_D
453. not 438 cC for AIX User s Guide Example The following example uses these symbols to show padding and boundaries p padding halfword boundary byte boundary For pragma options align packed struct char a double b f B pragma options align reset sizeof B The layout of B is a b b b b b b Packed Bit Fields The following rules apply when laying out packed bit fields e An individual bit field can be at most 32 bits long e Bit fields are packed together into the current word If a bit field extends beyond the current word it starts at the next byte boundary e A bit field of width zero causes the next class member to start at the next byte boundary If the zero width bit field is already at a byte boundary the next structure member starts at this boundary e A nonbit field following a bit field is aligned on the next byte boundary Example pragma options align packed struct mta g int b 10 int c 12 int d 43 inte 3 int 0 int FT B char g A pragma options align reset sizeof A The layout of A is Member Name Displacement bytes bits o0oQqnoddodw NO Y Appendix H RISC System 6000 Alignment Rules 439 Macintosh and Twobyte Alignment Rules All unions and structures are halfword aligned regardless of their members Within the aggregate members are aligned according to their type The size of types for the Macintosh system is the same as on
454. not valid results in undefined behavior Example This example creates a user heap and allocates memory from it with _debug_ucalloc It then attempts to write to memory that was not allocated When _debug_free is called uheap_check detects the error generates several messages and stops the program Note You must compile this example with the qheapdebug option to map the _ucalloc calls to _debug_ucalloc and free to _debug_free include lt stdlib h gt include lt stdio h gt include lt umalloc h gt include lt string h gt int main void Heap t myheap char ptr Use default heap as user heap myheap _udefault NULL if NULL ptr char ucalloc myheap 100 1 puts Cannot allocate memory from user heap exit EXIT_FAILURE memset ptr x 105 Overwrites storage that was not allocated free ptr return 0 BRK k k k k k k RRR k k KK ERR ER k kk RK ERE RRR ERE RK EKER RR RRR EKER ERE RK ERK kkk kk kkk Kk KRKK KK The output should be similar to End of allocated object 0x00073890 was overwritten at 0x000738f4 The first eight bytes of the memory block in hex are 7878787878787878 This memory block was re allocated at line number 14 in _debug_ucallo c Heap state was valid at line 14 of debug ucallo c Memory error detected at line 19 of debug ucallo c KK KK KKK KK ERK kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkx Appendix F C for AIX Debug Functions 42
455. now where to look to correct the problem You can create_heaps of regular memory or shared memory and you can have any number of heaps of any type See xviii for more information about the different types of memory for heaps The only limit is the spac available on your operating system your machine s memory and swapper size minus the memory required by other running applications C for AIX provides heap specific versions of the memory management functions for example umalloc and so on Debug versions of all memory management functions are provided including the heap specific ones C for AIX also provides additional functions that you can use to create and manage your own heaps of memory such as udefault Related Reading Types of Memory There are two types of memory 1 Regular memory Most programs use regular memory This is the type provided by the default runtime heap 2 Shared memory Heaps of shared memory can be shared between processes or applications If you want other processes to use the heaps you have created you must pass them the heap handle and give them access to the heap Use ucreate to create the heap Related Reading Debugging Memory Heaps C for AIX provides two sets of functions for debugging your memory problems 1 Debug versions of all memory management functions 2 Heap checking functions similar to those provided by other compilers Debug Memory Management Functions Debug versions of t
456. ns Are declarations that allocate storage for data objects or define a body for functions An object definition allocates storage and may optionally initialize the object 174 C for AIX User s Guide A function declaration precedes the function body The function body is a compound statement that can contain declarations and statements that define what the function does The function declaration declares the name its parameters and the data type of the value it returns A program must contain at least one function declaration If the program contains only one function declaration the function must be called main If the program contains more than one function declaration only one of the functions can be called main Any additional functions called main are ignored By convention main is the starting point for running a program The main function can in turn call other functions A program usually stops running at the first encounter of any of the following e The end of the main function e A return statement in the main function e An exit function call A C program can contain any number of directives declarations and definitions Before the C program is compiled the preprocessor filters out preprocessor directives that may change the files Preprocessor directives are completed macros are expanded and a temorary source file is created containing C statements completed directives declarations and definitions lt is sometimes useful
457. ns for future extensions are implemented e C for AIX requires that pragma options align suboption appears before the structure definition XL C allows the pragma to appear anywhere before the last closing brace of the structure definition e long long type is supported even under ANSI mode long long is recognized by all of the invocation commands except for ic89 and c89 which disable it by specifying the qnolonglong option e Invoking the compiler does not define _ANSI_C SOURCE unless you use the ic89 or c89 invocation commands or unless you include standards h This is because there are many useful definitions in header files that are not detected when _ANSI_C SOURCE is in effect You can define _ANSIC SOURCE by supplying D_ANSI_C_ SOURCE at compiler invocation 468 cC for AIX User s Guide Appendix K National Languages Support in the C for AIX Compiler This and related pages summarize the national language support NLS specific to the C for AIX Compiler Note You must specify the qmbcs option to use multibyte characters anywhere in your program Support for multibyte characters includes support for wide characters Generally wide characters are permitted anywhere multibyte characters are but they are incompatible with multibyte characters in the same string because their bit patterns differ Wherever permitted you can mix single byte and multibyte characters in the same string See Restrictions page zi for more informatio
458. nstant A number containing any digits 0 through 9 that does not begin with O zero declaration Establishes the names and characteristics of data objects and functions used in a program declarator Designates a data object or function declared Initializations can be performed in a declarator default A value attribute or option that is assumed when no alternative is specified by the programmer default clause In a switch statement the keyword default followed by a colon and one or more statements When the conditions of the specified case labels in the switch statement do not hold the default clause is chosen default initialization The initial value assigned to a data object by the compiler if no initial value is specified by the programmer extern and static variables receive a default initialization of zero while the default initial value for auto and register variables is undefined define directive A preprocessor directive that causes the preprocessor to replace an identifier or macro call with specified code definition A declaration that allocates storage and may initialize a data object or specify the body of a function do statement A looping statement that contains the word do followed by a statement the action the word while and an expression in parentheses the condition double byte character set DBCS A set of characters in which each character is represented by 2 bytes of storage Appendix O Glossa
459. nt enum music ROCK JAZZ NEW WAVE CLASSICAL enum music listening type using the command xlc yourfile c only the enum variable first_order will be minimum sized that is enum variable first_order will only occupy 1 byte of storage The other two enum variables test_enum and listening_type will be of type int and occupy 4 bytes of storage Related Reading extchk Option Type Default Value pragma options Syntax gextchk qnoextchk EXTCHK NOEXTCHK Purpose Generates bind time type checking information and checks for compile time consistency Notes qextchk checks for consistency at compile time and detects mismatches across compilation units at link time 258 C for AIX User s Guide qextchk does not perform type checking on functions or objects that contain references to incomplete types Example To compile myprogram c so that bind time checking information is produced enter xlc myprogram c qextchk Related Reading Option Type Default Value pragma options e Syntax f filename Purpose Linkage editor Id command option only Passes to the linkage editor the filename of a file containing a list of input files to be processed Notes Each line in filename is treated as if it were listed separately on the Id linkage editor command line Lines in this file can contain the following shell pattern characters to designate multiple object files e asterisk e left bracket e right brac
460. nt limits are set in the usr include float h header file described in Header Files Overview in the AIX Version 4 Files Reference When an integral value is converted to a floating point number that cannot exactly represent the original value the direction of truncation depends on the compile time rounding mode set by the y compiler option 3 2 1 3 When a floating point number is converted to a narrower floating point number the direction of truncation or rounding depends on the rounding mode set by the y compiler option 3 2 1 4 Using 16 byte long doubles qldbl128 Option The mathematical functions contained in the lt math hs header file such as cosl tanl fmodl have been updated to work with 16 byte long double floating point numbers The input output functions in the lt stdio h gt header file such as printf scanf vsprintf have been updated to work with 16 byte long double floating point numbers A new function atold which converts a string to a long double representation has been added to the existing string to number functions strtod strtol and strtoul Alignment Rules If the first member of a union or structure is a long double the aggregate is aligned on a 128 bit boundary Other aggregates and long double identifiers are aligned on a 32 bit boundary If qalign natural is specified all long doubles are aligned on a 128 bit boundary regardless of their placement in a union or structure Appendix I
461. nt types are never aliased In other words in the compilation unit no two pointers of different types will point to the same storage location qgASSert ALLPtrs Pointers are never aliased this implies qassert typeptr Therefore in the compilation unit no two pointers will point to the same storage location qgASSert ADDRtaken Variables are disjoint from pointers unless their address is taken Any class of variable for which an address has not been recorded in the compilation unit will be considered disjoint from indirect access through pointers Related Reading attr Option Type Default Value pragma options 238 C for AIX User s Guide Syntax qattr qattr full qnoattr ATTR ATTR FULL NOATTR Purpose Produces a compiler listing that includes an attribute listing for all identifiers Notes qgattr full Reports all identifiers in the program gattr Reports only those identifiers that are used This option does not produce a cross reference listing unless you also specify qxref The qnoprint option overrides this option lf qattr is specified after qattr full it has no effect The full listing is produced Example To compile the program myprogram c and produce a compiler listing of all identifiers enter xlc myprogram c qxref qgattr full A typical cross reference listing has the form Identifier name Description of the item S EY auto int in function adder O 59 O 36 1224 0 45 122 IL Functi
462. nt variables are set each time the user logs in Setting Environment Variables in csh Shell To set the environment variables from the C shell use the following commands setenv LANG en_US setenv NLSPATH usr lib nls msg L N usr 1lib nls msg N In the C shell you cannot set the environment variables so that all users have access to them To set them for a specific user only add the commands to the file cshre in the user s home directory The environment variables are set each time the user logs in Related Reading 4 C for AIX User s Guide Chapter 3 Using the C for AIX Compiler You can use the C for AIX product as a C compiler for files with a c small c suffix The compiler processes your text based C program source files to create an executable object module The cc command is a tradional UNIX operating system command for invoking the C compiler Other compiler modes and their invocation commands described in this and related pages are specific to the C for AIX compiler Note Use of the xlc Command in this Information Throughout these information panels the xlc command is used to describe the actions of the compiler In most cases you should use the xlc command to compile your C source files The xlc_r and xlc128 commands specify additional libraries macros or options that are not automatically included or set by the xlc command Besides these differences these commands may be considered functionally equiv
463. nterpreted as an octal constant rather than as a decimal constant The following are examples of decimal constants 485976 433132211 20 5 Hexadecimal Values A hexadecimal constant begins with the 0 digit followed by either an x or X followed by any combination of the digits O through 9 and the letters a through f or A through F The letters A or a through F or f represent the values 10 through 15 respectively gt gt 0x 7 aig to to x ___________ OX aagit foto S The following are examples of hexadecimal constants 0x3b24 OXF96 0x21 0x3AA 0X29b OX4bD Octal Values An octal constant begins with the digit O and contains any of the digits 0 through 7 i ee ee gt The following are examples of octal constants 0 0125 034673 03245 Floating Point Constants A floating point constant consists of e An integral part e A decimal point e A fractional part e An exponent part e An optional suffix Chapter 6 The C Language 49 Both the integral and fractional parts are made up of decimal digits You can omit either the integral part or the fractional part but not both You can omit either the decimal point or the exponent part but not both A suffix of f or F indicates a type of float and a suffix of or L indicates a type of long double If a suffix is not specified the floating point constant has a type double A plus or minus symbol can precede a floating point constant Howev
464. ntf destination is originally s n destination return string strcpy destination source printf After strcpy destination becomes s n n destination return 0 BRK k k k k k KEE KER KEKE RR ERR ERR ERE RRR ERK ERK ER KERR RRR k k kk kk kkk kkk ERR The output should be similar to destination is originally abcdefg End of allocated object 0x00073c80 was overwritten at 0x00073c8a The first eight bytes of the memory block in hex are 3132333435363738 This memory block was re allocated at line number 13 in strcpy c Appendix F C for AIX Debug Functions 421 Heap state was valid at line 14 of strcpy c Memory error detected at line 17 of strcpy c KKK KKK KEE KEK RRR EK RRR RK KKK ER ERR KK ERK ERR ERE RK ERK ER ERR KERR KERR kkk KERERERKE Related Readin _debug_sirncat Concatenate Strings Format include lt string h gt char debug strncat char stringl const char string2 size_t count const char file size t line Language Level Extension _debug_strncat is the debug version of strncat Like strncat it appends the first count characters of string2 to stringl and ends the resulting string with a null character 0 If count is greater than the length of string2 the length of string2 is used in place of count _debug_strncat validates the heap after appending the characters and performs this check only when the target is within a heap _debug_strncat makes an implicit call to heap chec
465. nvoked program e A function pointer is passed as a pointer to the routine s function descriptor The first word contains the entry point address See A for more information Related Reading Interlanguage Calls Rules for Passing Parameters by Value The following is an example of a call to a prototyped function int i JaK double dl d2 float fl Short int sl char c void f int int int double float char double short Tt i je Ks dl fls c d2 51 The function call results in the following storage mapping Chapter 8 Using C for AIX with Other Programming Languages 211 Storage mapping of the Will be passed in PARM area on the Stack 12 FP1 R6 R unused di 16 RY 24 vere eere eere oo right justified for a nonprototyped function 20 32 Stack 36 eree eere eere l right justified for a nonprototyped C function Notes 1 A parameter is guaranteed to be mapped only if its address is taken 2 Data with less than fullword alignment is copied into high order bytes Because the function in the example is prototyped the mapping of parameters c and s1 is right justified 3 The parameter list is a conceptually contiguous piece of storage containing a list of words For efficiency the first 8 words of the list are not actually stored in the space reserved for them but passed in GPR3 GPR10 Furthermore the first 13 floating point value parameter values are not passed in GPRs but
466. ny compilers perform all floating point arithmetic in double precision only the C compiler extended language level performs double precision arithmetic when all operands have type float When on operand has type float and another operand has type double or long double the compiler converts the float to the equivalent double or long double value Integral to Floating Point The compiler converts narrower integral values to equivalent floating point values Unsigned Arithmetic Expansion The compiler converts narrower unsigned arithmetic values to wider unsigned arithmetic values by padding the values with zeros Signed Arithmetic Expansion The language does not define how narrower signed arithmetic values are converted to wider signed arithmetic values When a narrower arithmetic value is converted to a wider signed arithmetic value the compiler pads bits located to the left of the value with a copy of the sign bit Pointer Conversions Pointer to Pointer When two pointers to objects of the same type are subtracted the compiler performs the operation on the values of the pointers and divides the result by the length of the objects to which the pointers refer The result is an integer that indicates the distance between the specified objects in the array For example if p points to the second element in an array and q points to the fifth element in the array the expression p q yields 3 Integral to Pointer When an integral value is subtracted fr
467. o a void provided that a void has sufficient bits to hold it You can convert an expression with type array of some type to a pointer to the initial element of the array except when the expression is used as the operand of the amp address operator or the sizeof operator Chapter 6 The C Language 75 You can convert an expression with a type of function returning T to a pointer to a function returning T except when the expression is used as the operand of the amp address operator the function call operator or the sizeof operator You can convert an integer value to an address offset For more information on pointer conversions see Pointer Arithmetic page bo Function Argument Conversions If no function prototype declaration is visible when a function is called the compiler can perform default argument promotions which consist of the following e Integral promotions e Arguments with type float are converted to type double Other Conversions By definition the void type has no value Therefore it cannot be converted to any other type and no other value can be converted to void by assignment However a value can be explicitly cast to void No conversions between structure or union types are allowed You can convert from an enum to any integral type but not from an integral type to an enum Related Reading sizeof page 122 Arithmetic Conversions Most operators perform type conversions to bring the
468. o be private to each thread Each new private object is initialized as if there was an implied declaration within the statement block Data variables in list are separated by commas nowait Use this clause to avoid the implied barrier at the end of the single directive Only one nowait clause can appear on a given single directive Notes An implied barrier exists at the end of a parallelized statement block unless the nowait clause is specified Related Reading pragma omp master Preprocessor Directive The omp master directive identifies a section of code that must be run only by the master thread Syntax pragma omp master statement_block Notes Threads other than the master thread will not execute the statement block associated with this construct Appendix E Parallel Processing Facilities 395 No implied barrier exists on either entry to or exit from the master section Related Reading pragma omp critical Preprocessor Directive The omp critical directive identifies a section of code that must be executed by a single thread at a time Syntax pragma omp critical name statement_block where name can be used to optionally identify the critical region Identifiers naming a critical region have external linkage Notes The compiler reports an error if you try to branch into or out of a critical section Some situations that will Cause an error are e Accritical section that contains the return statement e
469. o defined when the compiler is in a mode that permits long long int and unsigned long long int types Sets the number of bits to use when representing the value of a long double The available options are 64 and 128 bits Defined if the compiler is using the 64 bit data model This data model is used when compiling programs for 64 bit mode This macro should not be user defined or redefined Instructs the compiler to generate substitute code for calls to some math functions available in the standard C runtime libraries if appropriate The functions handled this way are defined as replacement text for macros that begin with two underscores _ in the usr vac include math h header file Macro defined when the qsmp omp compiler option is set to enable full compliance to the OpenMP API specification Indicates the operating system is AIX 4 1 or higher Allows only language constructs that conform to the most recent level of the SAA C standards Defined using the pragma langlvl directive or the qlanglvl compiler option Allows only language constructs that conform to the most recent level of the SAA Level 2 C standards Defined using the pragma langlvl directive or the qlanglvl compiler option Instructs the compiler to generate substitute code for calls to some string functions available in the standard C runtime libraries if appropriate The functions handled this way are defined as replacement text for macros that begi
470. o nothing delay time between each scan of the work queue Each unit of delay is achieved by running a single no memory access delay loop The default value for num is 500 Dynamic Profiling Options profilefreq num parthreshold mSec seqthreshol d mSec num represents the sampling rate at which each loop is revisited to determine appropriateness for parallel processing The run time library uses dynamic profiling to dynamically tune the performance of automatically parallelized loops Dynamic profiling gathers information about loop running times to determine if the loop should be run sequentially or in parallel the next time through Threshold running times are set by the parthreshold and seqthreshold dynamic profiling options described below If num is 0 all profiling is turned off and overheads that occur because of profiling will not occur If num is greater than 0 running time of the loop is monitored once every num times through the loop The default for num is 16 The maximum sampling rate is 32 Higher values of num are changed to 32 mSec specifies the expected running time in milliseconds below which a loop must be run sequentially mSec can be specified using decimal places if parthreshold is set to 0 a parallelized loop will never be serialized by the dynamic profiler The default value for mSec is 0 2 milliseconds mSec specifies the expected running time in milliseconds beyond which a loop that has been serializ
471. o x y p_ to x The following statement assigns the value of y to the variable that p_to_ x references char y p to x p_to_x y You cannot use pointers to reference bit fields or objects having the register storage class specifier Pointer Arithmetic You can perform a limited number of arithmetic operations on pointers These operations are e Increment and decrement e Addition and subtraction e Comparison e Assignment The increment operator increases the value of a pointer by the size of the data object the pointer refers to For example if the pointer refers to the second element in an array the makes the pointer refer to the third element in the array The decrement operator decreases the value of a pointer by the size of the data object the pointer refers to For example if the pointer refers to the second element in an array the makes the pointer refer to the first element in the array You can add a pointer to an integer but you cannot add a pointer to a pointer If the pointer p points to the first element in an array the following expression causes the pointer to point to the third element in the same array p pt2 If you have two pointers that point to the same array you can subtract one pointer from the other This operation yields the number of elements in the array that separate the two addresses that the pointers refer to You can compare two pointers with the following operator
472. ociative and commutative operators you can use parentheses to specify the grouping of operands with operators The parentheses in the following expression guarantee the order of grouping operands with the operators x f g h 118 C for AIX Users Guide Array Subscripts A primary expression followed by an expression in square brackets specifies an element of an array The expression within the square brackets is referred to as a subscript The primary expression must have a pointer type and the subscript must have integral type The result of an array subscript is an lvalue The first element of each array has the subscript 0 The expression contract 35 refers to the 36th element in the array contract In a multidimensional array you can reference each element in the order of increasing storage locations by incrementing the rightmost subscript most frequently For example the following statement gives the value 100 to each element in the array code 4 3 6 for first 0 first lt 3 first for second 0 second lt 2 second for third 0 third lt 5 third code first second third 100 Structure and Union Member Specification Two primary operators let you specify structure and union members The dot a period and arrow formed by a minus and a greater than symbol operators are always preceded by a primary expression and followed by an identifier When you use the dot operator the pr
473. ode located in a preprocessor define directive main function An external function that has the identifier main Each program must have exactly one external function named main Program execution begins with this function N new line character A control character that causes the print or display position to move to the first position on the next line This character is represented by n in C NULL A pointer that has a value 0 is guaranteed not to point to any data object The pointer can be converted to any pointer type null character NUL The character hex 00 used to represent the absence of a printed or displayed character null statement A C statement that consists solely of a semicolon O object code Machine executable instructions usually generated by a compiler from source code written in a higher level language For programs that must be linked object code consists of relocatable machine code octal A base eight numbering system octal constant The digit O zero followed by any digits 0 through 7 operand An entity on which an operation is performed operator A symbol such as that represents an operation in this case addition subtraction multiplication overflow That portion of an operation s result that exceeds the capacity of the intended unit of storage overflow condition A condition that occurs when a portion of the result of an operation exceeds the capacity of the intended u
474. of TRAP signals In these respects the implementation of qflttrap does not fully support the exception handling environment suggested by the IEEE floating point standard Floating point exceptions are described in the AIX Version 4 Assembler Language Reference The sample AOIG lt exceptions Related Reading Sample TRAP Signal Handler The sample C code below defines a TRAP signal handler fhandler_ It uses the fp_enable and fp_disable_all support routines from the Base Operating System BOS Runtime Services to enable or disable floating point exceptions The sample handler prints an error message indicating the type and location of the operation that caused the exception You can use a load map and compiler listing to show the location and identify the source code line that generated the exception The signal handling code also allows the results of failing instructions to be modified to specific values The program myprogram c would be compiled with the command xlc c myprogram c Chapter 4 Advanced Compiler Usage 31 and the resulting object file would be linked with other C object files produced using the flttrap option Note This code is for illustrative purposes even when support code such as this is used the implementation of flttrap does not fully support the exception handling environment suggested by the IEEE floating point standard Exception handling support for use with the flttrap compiler option
475. of bitwise shifts on such values is unpredictable If the right operand has the value O the result is the value of the left operand after the usual arithmetic conversions The lt lt operator fills vacated bits with zeros For example if left_op has the value 4019 the bit pattern in 32 bit format of left_op is 00000000000000000000111110110011 The expression left_op lt lt 3 yields 00000000000000000111110110011000 The following table shows the behavior of the gt gt operator Left Operand Type Result of gt gt unsigned type The vacated bits are filled with zeros Nonnegative unsigned type The integral part of the quotient of the left operand divided by the quantity 2 raised to the power of the right operand The vacated bits of a signed value are filled with a copy of the sign bit of the unshifted value Negative signed type The language does not specify how the vacated bits produced by the gt gt operator are filled 126 C for AIX Users Guide Relational The relational operators compare two operands and determine the validity of a relationship If the relationship stated by the operator is true the value of the result is 1 If false the value of the result is 0 The result is not an lvalue The following table describes the four relational operators Operator Usage Indicates whether the value of the left operand is less than the value of the right operand Indicates whether the value of the left
476. of bytes of code that will be generated Larger values for this number allow the compiler to inline larger subprograms more subprogram calls or both This argument is implemented only when inline auto is on inline threshold size Specifies the upper size limit of functions to be inlined where size is a value as defined under inline limit This argument is implemented only when inline auto is on isolated name name Specifies a list of isolated functions that are not compiled with IPA Neither isolated functions nor functions within their call chain can refer to global variables level n Specifies the optimization level for interprocedural analysis The default level is 1 Valid levels are as follows 0 Does only minimal interprocedural analysis and optimization 1 Turns on inlining limited alias analysis and limited call site tailoring 2 Performs full interprocedural data flow and alias analysis list name short long Specifies that a listing file be generated during the link phase The listing file contains information about transformations and analyses performed by IPA as well as an optional object listing generated by the back end for each partition This option can also be used to specify the name of the listing file If listings have been requested using either the qlist or qipa list options and name is not specified the listing file name defaults to a lst The long and short suboptions can be used to request more or le
477. of the file file and the line number line where the storage is allocated This information can be used later by the _uheap_ check udump_allocated or udump_allocated_delta functions debug _umalloc also sets all the memory it allocates to OxAA this can help you debug problems where your program uses the data in the memory without initializing it _debug_umalloc works just like debug malloc except that you specify the heap to use _debug_ malloc always allocates from the default heap If the heap does not have enough memory for the request debug umalloc calls the getmore_fn that you specified when you created the heap with _ucreate To use _debug_umalloc you must compile with the debug memory qheapdebug compiler option This option maps all _umalloc calls to debug _umalloc Note The qheapdebug option maps all calls to memory management functions including heap specific versions to their debug counterparts To prevent a call from being mapped parenthesize the function name To reallocate or free memory allocated with _debug_umalloc use the non heap specific debug_realloc and debug_free These functions always check what heap the memory was allocated from Return Value _debug_umalloc returns a pointer to the reserved space If size was specified as zero or the getmore_fn cannot provide enough memory _debug_umalloc returns NULL Passing _debug_umalloc a heap that is not valid results in undefined behavior Example This example cre
478. of the left operand is equal to the value of the right operand Indicates whether the value of the left operand is not equal to the value of the right operand Both operands must have arithmetic types or be pointers to the same type or one operand must have a pointer type and the other operand must be a pointer to void or NULL The result has type int If the operands have arithmetic types the usual arithmetic conversions on the operands are performed If the operands are pointers the result is determined by the locations of the objects to which the pointers refer If one operand is a pointer and the other operand is an integer having the value 0 the expression is true only if the pointer operand evaluates to NULL The operator evaluates to true if the pointer operand does not evaluate to NULL You can also use the equality operators to compare pointers to members that are of the same type but do not belong to the same object The following expressions contain examples of equality and relational operators time lt max_time status lt complete letter EOF Note The equality operator should not be confused with the assignment operator For example if x 3 evaluates to 1 if x is equal to three Equality tests like this should be coded with Spaces between the operator and the operands to prevent unintentional assignments is taken to be true because x 3 evaluates to a non zero value 3 The expression
479. om a pointer the compiler multiplies the integral value by the length of the object to which the pointer refers to produce an address offset which can be added or subtracted from the pointer value The result is a pointer having the same type as the original pointer that refers to an object assumed to be in the same array void ConversionsA program cannot use or apply conversions to the nonexistent value of a void object To convert the result of a function call to type void use the cast operator Such a conversion discards the value of a function call used in an expression statement For example the following statement discards the result of the function call add void add volatile Conversions volatile to Nonvolatile Through an explicit cast you can assign the address of a volatile data object to a pointer that is defined as pointing to a nonvolatile data object If the volatile object is referenced through such a pointer the result is undefined Nonvolatile to volatile You can assign the address of a nonvolatile data object that is defined as pointing to a volatile data object If the nonvolatile object is referenced through such a pointer the compiler treats the nonvolatile object as a volatile object Related Reading Summary of C Language Level Conflicts This section summarizes for quick reference the conflicts listed in the related pages 170 C for AIX Users Guide Note The following table shows only those featu
480. on nonprototyped No type information is provided in the function declaration Type information for each parameter in a function definition is provided after a list of parameters Prototypes are the preferred style of function declaration The ANSI C standard has declared the nonprototyped style obsolete Calling Functions and Passing Arguments A function call specifies a function name and a list of arguments The calling function passes the value of each argument to the specified function The argument list is surrounded by parentheses and each argument is separated by a comma The argument list can be empty The arguments to a function are evaluated before the function is called When an argument is passed in a function call the function receives a copy of the argument value If the value of the argument is an address the called function can use indirection to change the contents pointed to by the address If a function or array is passed as an argument the argument is converted to a pointer that points to the function or array The order in which arguments are evaluated and passed to the function is implementation defined For example the following sequence of statements calls the function tester int x x l tester x x Chapter 6 The C Language 77 The call to tester in the example may produce different results on different compilers Depending on the implementation x may be evaluated first or x may be evaluated first
481. on Directives A preprocessor conditional compilation directive causes the preprocessor to conditionally suppress the compilation of portions of source code These directives test a constant expression or an identifier to determine which tokens the preprocessor should pass on to the compiler and which tokens should be bypassed during preprocessing The directives are e if e ifdef e ifndef e else e elif e endif For each if ifdef and ifndef directive there are zero or more elif directives zero or one else directive and one matching endif directive All the matching directives are considered to be at the same nesting level You can nest conditional compilation directives In the following directives the first else is matched with the if directive ifdef MACNAME tokens added if MACNAME is defined if TEST lt 10 tokens added if MACNAME is defined and TEST lt 10 else tokens added if MACNAME is defined and TEST gt 10 x endif else tokens added if MACNAME is not defined x endi f Each directive controls the block immediately following it A block consists of all the tokens starting on the line following the directive and ending at the next conditional compilation directive at the same nesting level Each directive is processed in the order in which it is encountered If an expression evaluates to zero the block following the directive is ignored When a block following a p
482. on causes the compiler to generate object code that detects the conversion of a single precision signalling NaN NaNS to double precision By default the compiler generates object code that detects the use of a NaNS in all other situations required by the IEEE standard Very few programs actually require checks for NaNS A NaNS cannot be produced by any floating point operation and must instead be explicitly created A program only needs to be compiled with the qfloat nans option if it explicitly creates a signalling NaN qfloat hsfit The qfloat hsflt option improves the performance of floating point computations by suppressing all rounding operations and by performing conversions from floating point to integer with inline code This option is intended for knowledgeable programmers in specific applications where the computational characteristics of a program are known To safely use the hsflt option a program must never attempt to assign floating point results to single precision variables unless the results are known to be within the allowable range of single precision values In addition if any floating point numbers are converted to integers the floating point numbers must be within the representable range of integers If the hsflt option is used in cases where a program does not have these properties the program may produce incorrect results without warning When the computational characteristics of a program are not known use hssngl no
483. on invocation Column number Line number File Function definition Related Reading To xret_on page J Option Type Default Value pragma options a Syntax B Bprefix B tprograms Bprefix tprograms Purpose Determines substitute path names for the compiler assembler linkage editor and preprocessor Notes The optional prefix defines part of a path name to the new programs It must end in To form the complete path name for each program the C for AIX compiler adds prefix to the standard program names for the compiler assembler linkage editor and preprocessor Appendix A Compiler Options 239 Use this option if you want to keep multiple levels of some or all of the C for AIX compiler executables and have the option of specifying which one you want to use If Bprefix is not specified the default path is used B tprograms specifies the programs to which the B prefix name is to be appended The Bprefix torogramsoptions override the Fconfig_file option Example To compile myprogram c using a substitute xle compiler in lib tmp mine enter xlc myprogram c B 1lib tmp mine To compile myprogram c using a substitute linkage editor in lib tmp mine enter xlc myprogram c B lib tmp mine t1 Related Reading bitfields Option Type Default Value pragma options fp aoptin unsigned Syntax qbitfields suboption Purpose Specifies if bitfields are signed By default bitfields are unsigned
484. on paqe l4 goto A goto statement causes your program to unconditionally transfer control to the statement associated with the label specified on the goto statement P gto label icentiiier a Because the goto statement can interfere with the normal sequence of processing it makes a program more difficult to read and maintain Often a break statement a continue statement or a function call can eliminate the need for a goto statement If you use a goto statement to transfer control to a statement inside of a loop or block initializations of automatic storage for the loop do not take place and the result is undefined The label must appear in the same function as the goto Related Reading Chapter 6 The C Language 151 Example Using the goto Statement The following example shows a goto statement that is used to jump out of a nested loop This function could be written without using a goto statement void display int matrix 3 3 int i j for i 0 i lt 3 i for j 0 j lt 33 j if matrix i j lt 1 matrix i j gt 6 goto out_of bounds printf matrix d d d n i j matrix i j returns out_of_bounds printf number must be 1 through 6 n Related Reading Egata an page 151 if else An if statement lets you conditionally process a statement when the specified test expression evaluates to a nonzero value The expression must evaluate to a sc
485. on will override earlier options For example specifying qlanglvl ansi extended will result in the compiler using the extended language level The exceptions to this rule are the noucs and ucs suboptions which do not override and are not overridden by other qlanglvl suboptions Exceptions to the ansi mode addressed by classic are as follows Tokenization Tokens introduced by macro expansion may be combined with adjacent tokens in some cases Historically this was an artifact of the text based implementations of older preprocessors and because in older implementations the preprocessor was a separate program whose output was passed on to the compiler Appendix A Compiler Options 287 Preprocessing directives For similar reasons tokens separated only by a comment may also be combined to form a single token Here is a summary of how tokenization of a program compiled in classic mode is performed 1 At a given point in the source file the next token is the longest sequence of characters that can possibly form a token For example i j is tokenized as i j even though i j may have resulted in a correct program 2 If the token formed is an identifier and a macro name the macro is replaced by the text of the tokens specified on its define directive Each parameter is replaced by the text of the corresponding argument Comments are removed from both the arguments and the macro text 3 Scanning is resumed at th
486. ong int are considered as possible aliases of a long long int or unsigned long long int e The attribute listing will display long long integer for signed long long int identifiers and unsigned long long integer for long long int identifiers e In interlanguage calls a C signed long long int maps to a Fortran INTEGER 8 and an unsigned long long int maps to a Fortran LOGICAL 8 Other system limits are set in the usr include sys limits h file The limits h header file is described in the Header Files Overview of the AIX Version 4 Files Reference 450 C for AIX User s Guide Related Reading Implementation Dependency Floating Point Types F 3 6 The scaled value of a floating point constant that is in the range of the representable value for its type is controlled at compile time by the y compiler option and conforms to the IEEE standard for binary floating point arithmetic 3 1 3 1 The following table shows the storage occupied and the range of various floating point types 3 1 2 5 Type Size bits Range of base Range of Decimal Values Precision 10 Exponents in float h decimal digits 37 to 38 1 175494351E 38 to 3 402823466E 38 7 double 64 307 to 308 2 2250738585072014E 308 to 19 1 7976931348623157E 308 9 long double 64 307 to 308 2 2250738585072014E 308 to 1 1 7976931348623157E 308 long double 128 307 to 308 2 2250738585072014E 308 to 31 qldbl128 1 7976931348623157E 308 option Other floating poi
487. ons D AIX D AIX32 D AIX41 D_IBMR2 D POWER bpT 0x10000000 bpD 0x20000000 ldopt b o e u R H Y Z L T A k j hdlibs L usr vac lib 1hmd xlCcopt qansialias smplibraries 1xlsmp optlibraries 1 xlopt resexp usr vacpp lib res exp genexports usr vac bin CreateExportList vac cfg 43 Compiler Configuration File C COPYRIGHT International Business Machines Corp 1991 1999 US Government Users Restricted Rights Use duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp IX header files L lib profiled L usr lib profiled COMPONENT NAME CC C for AIX Compiler x FUNCTIONS C C Configuration file ORIGINS 27 All Rights Reserved Licensed Materials Property of IBM ANSI C compiler UN X C use DEFLT crt lib crt0 o mcrt lib mcrt0 o gert lib gcrt0 o libraries lc proflibs options qansialias C compiler extended mode cc use DEFLT crt lib crt0 o Appendix L C for AIX Files 477 mert lib mcrt0 o gcrt lib gcrt0 o libraries lc proflibs L lib profiled L usr lib profiled options qlanglvl extended qnoro qnoroconst xlc128 use DEFLT crt lib crt0 o mcrt lib mcrt0 o gcrt lib gcrt0 o libraries 1c128 lc proflibs L lib profiled L usr lib profiled options qansia lias qldbl128 C compiler extended mode cc128 use DEFLT crt lib crt0 o mert 1ib mcrt0 o gcrt lib gc
488. ons dataimported DATALOCal DATAIMPorted Syntax qdatalocal qdatalocal names qdataimported qdataimported names DATALOCAL DATALOCAL names DATAIMPORTED DATAIMPORTED names Purpose Mark data as local or imported Notes Local variables are statically bound with the functions that use them qdatalocal changes the default to assume that all variables are local qdatalocal names marks the named variables as local where names is a list of identifiers separated by colons The default is not changed Performance may decrease if an imported variable is assumed to be local Imported variables are dynamically bound with a shared portion of a library qdataimported changes the default to assume that all variables are imported qdataimported names marks the named variables as imported where names is a list of identifiers separated by colons The default is not changed Conflicts among the data marking options are resolved in the following manner Options that list variable names The last explicit specification for a particular variable name is used Options that change the default This form does not specify a name list The last option specified is the default for variables not explicitly listed in the name list form Appendix A Compiler Options 251 Related Reading dbxextra Option Type Default Value pragma options a e Syntax qdbxextra qnodbxextra Purpose Specifies that all typedef declarations s
489. ons info suboption suboption or pragma options noinfo forms of this compiler option to temporarily enable or disable messages in a particular section of program code and pragma options info reset to return to your initial qinfo settings Available suboptions for qinfo compiler option are Suboptions Description all Turns on all diagnostic messages for all groups Note The qinfo and qinfo all forms of the option have the same effect private Lists shared variables made private to a parallel loop reduction Lists all variables that are recognized as reduction variables inside a parallel loop Appendix A Compiler Options 2 75 Suboptions Description group Turns on specific groups of messages where group can be one or more of group Type of messages returned cmp Possible redundancies in unsigned comparisons cnd Possible redundancies or problems in conditional expressions cns Operations involving constants cnv Conversions dcl Consistency of declarations eff Statements with no effect enu Consistency of enum variables ext Unused external definitions gen General diagnostic messages gnr Generation of temporary variables got Use of goto statements ini Possible problems with initialization inl Functions not inlined Tan Language level effects obs Obsolete features ord Unspecified order of evaluation par Unused parameters por Nonportable language constructs ppc Possible problems with using the preprocessor ppt Tra
490. operand is greater than the value of the right operand Indicates whether the value of the left operand is less than or equal to the value of the right operand Indicates whether the value of the left operand is greater than or equal to the value of the right operand Both operands must have arithmetic types or be pointers to the same type The result has type int If the operands have arithmetic types the usual arithmetic conversions on the operands are performed When the operands are pointers the result is determined by the locations of the objects to which the pointers refer If the pointers do not refer to objects in the same array the result is not defined Relational operators have left to right associativity For example the expression a lt b lt c is interpreted as a lt b lt Cc If the value of a is less than the value of b the first relationship is true and yields the value 1 The compiler then compares the value 1 with the value of c Chapter 6 The C Language 127 Equality The equality operators like the relational operators compare two operands for the validity of a relationship The equality operators however have a lower precedence than the relational operators If the relationship stated by an equality operator is true the value of the result is 1 Otherwise the value of the result is O The following table describes the two equality operators Operator Usage Indicates whether the value
491. operand7 is evaluated first and then only one of the two remaining operands is evaluated If that operand s expression contains or returns arithmetic types the usual arithmetic conversions are performed on that expression s values The conditional expression contains one two part operator The symbol follows the condition and the appears between the two action expressions All expressions that occur between the and are treated as one expression Chapter 6 The C Language 131 The first operand must have a scalar type The type of the second and third operands must be one of the following e an arithmetic type e a compatible pointer structure or union type e void The second and third operands can also be a pointer or a null pointer constant Two object are compatible when they have the same type but not necessarily the same type qualifiers volatile or const Pointer objects are compatible if they have the same type or are pointers to void The first expression is evaluated first If the first expression returns a non zero value the second expression is evaluated converted to the result type and becomes the value of the conditional expression The third operand is ignored in this case If the first expression instead returns a zero value the third operand is evaluated converted to the result type and becomes the value of the conditional expression The second expression is ignored in this case The types of the se
492. operands of an expression to a common type or to extend short values to the integer size used in machine operations The conversions depend on the specific operator and the type of the operand or operands However many operators perform similar conversions on operands of integer and floating point types These standard conversions are known as the arithmetic conversions because they apply to the types of values ordinarily used in arithmetic Arithmetic conversions are used for matching operands of arithmetic operators to a common type See ito see how operand type mismatches are resolved 76 CG for AIX Users Guide Related Reading Functions Functions specify the logical structure of a program and define how operations are implemented A function declaration consists of a return type a name and an argument list It is used to declare the format and existence of a function prior to its use A function definition contains a function declaration and the body of the function A function can have only one definition C functions can be declared or defined in two ways prototyped Type information is provided with each parameter The compiler uses the function prototype for argument type checking and argument conversions Prototypes can appear several times in a program provided the declarations are compatible They allow the compiler to check for mismatches between the parameters of a function call and those in the function declarati
493. or after the file name For example xlc qLIST qnomaf file c xlc file c qxref qsource Some options have suboptions You specify these with an equal sign following the qoption If the option permits more than one suboption a colon must separate each suboption from the next For example xlc qflag w e qattr full file c compiles the C source file file c using the option qflag to specify the severity level of messages to be reported the suboptions w warning for the minimum level of severity to be reported on the listing and e error for the minimum level of severity to be reported on the terminal The option qattr with suboption full will produce an attribute listing of all identifiers in the program Flag Options The compilers available on AIX systems use a number of common conventional flag options The C for AIX compiler supports these flags Lowercase flags are different from their corresponding uppercase flags For example c and C are two different compiler options c specifies that the compiler should only preprocess and compile and not invoke the linkage editor while C can be used with P or E to specify that user comments should be preserved The C for AIX compiler also supports flags directed to other AIX programming tools and utilities for example the AIX Id command The compiler passes on those flags directed to Id at link edit time Some flag options have arguments that form part of the flag For example
494. or after the function definition e before or after the function declaration e before or after a function has been referenced e inside or outside a function definition Related Reading pragma options Preprocessor Directive The pragma options directives specifies compiler options within your source program ee pragma options opion ea By default the options specified apply to the entire C source program If you specify more than one compiler option use a blank space to separate them Most pragma options directives must appear before any statements in your C program source Comments and blank lines however may precede the pragma options directive For example the first few lines of your C program can be a comment followed by the pragma options directive then the source x x The following is an example of a pragma options directive pragma options langlvl saa halt s spill 1024 source The rest of the source follows below For more information about compiler options refer to The following pragma options directives can appear anywhere in the source file Appendix D Preprocessor Directives and Related Information 375 e pragma options source e pragma options enum e pragma options align Some pragma options directives have corresponding preprocessor pragma directives These along with their required placement locations in a C program source are pragma options Name pragma Nam
495. orec_locks schedule sched_type n Notes Enables or disables parallelization of nested parallel constructs nonested_par is the default If one parallel construct is run as part of another parallel construct the execution of the nested construct is serialized by the compiler for better performance If nested_par is in effect nested parallel constructs are not serialized Notes 1 nested_par does not provide true nested parallelism because it does not cause new team of threads to be created for nested parallel regions Instead threads that are currently available are re used 2 This option should be used with caution Depending on the number of threads available and the amount of work in an outer loop inner loops could be executed sequentially even if this option is in effect Parallelization overhead may not necessarily be offset by program performance gains Enables or disables strict compliance with OpenMP C and C API specifications noomp is the default This mode allows for maximum program parallelization but may not be completely compliant to the OpenMP API specification If you specify the omp suboption the compiler disables automatic parallelization and warns of directives that are not OpenMP compliant The OPENMP macro is defined Certain other smp suboptions enable compiler parallelization features that do not comply with the OpenMP specification If they are specified together with the omp suboption a wa
496. ory mapped O Use the function __ iospace_synce I O Space Synchronization when all the multiple dispatch capabilities of the processor must be synchronized To use these built in functions effectively you should use pointers to volatile to access device registers and then place either of these built in functions at the completion of this access section of your code Related Reading 464 C for AIX Users Guide Example of Multiple Writes to a Single Register Consider a machine with a single register This register must be fed a sequence of four commands in exact order to form a complete instruction To prevent reordering of the command sequence the __iospace eieio function is used The sequence of commands is 1 load address 2 low order byte data 3 high order byte data 4 load word command Each set of instruction data needs to be synchronized typedef unsigned long data define COMMAND REG volatile data const OxFFFFFF20 define LOAD ADDRESS OxFFFF2000 define LOAD HIGH DATA OxFF define LOAD LOW DATA 0xA0 define LOAD COMMAND 0x10 void send _load_command COMMAND REG LOAD_ ADDRESS __jiospace eieio ensure the stores are ordered COMMAND REG LOAD_LOW DATA __jiospace eieio ensure the stores are ordered COMMAND REG LOAD_HIGH DATA __jiospace eieio ensure the stores are ordered COMMAND_REG LOAD_ COMMAND __jiospace eieio ensure the stores are ordered Relate
497. ose Specifies which files are included with include lt file_name gt and include file_name directives Notes If you specify qnostdinc the compiler will not search the directory usr include unless you explicitly add them with the ld rectory option If a full absolute path name is specified this option has no effect on that path name It will still have an effect on all relative path names qnostdinc is independent of qidirfirst qidirfirst searches the directory specified with ldirectory before searching the directory where the current source file resides The search order for files is described in Dire The last valid pragma options NO STDINC remains in effect until replaced by a subsequent pragma options NO STDINC Example To compile myprogram c so that the directory tmp myfiles is searched for a file included in myprogram c with the include myinc h directive enter xlc myprogram c qnostdinc I tmp myfiles Related Reading Appendix A Compiler Options 325 Strict Option Type Default Value pragma options Syntax qstrict qnostrict STRICT NOSTRICT Purpose Turns off aggressive optimizations that have the potential to alter the semantics of your program Notes qnostrict has no effect at O optimization level 0 qstrict turns off the following optimizations e Performing code motion and scheduling on computations such as loads and floating point computations that may tri
498. ource is a collection of one or more text source files written in the C programming language each of which can contain all or part of the functions that make up a C program The individual source files are compiled into object modules which can then be linked together to create an executable program You can use any text editor to create and edit a source file File Naming Conventions A file name can be up to 256 characters Longer names are truncated on the right The file name can contain lowercase and uppercase letters numbers underscores periods and other characters The AIX Version 4 Operating System distinguishes between uppercase and lowercase letters By convention C source files end with a c filename extension for example myprogram c The characters amp lt gt 2 have special meaning in the AIX system To use them in a file name you must place them inside quotation marks so that the shell does not interpret them For example my lt new gt program c Related Reading Internal Structure of a C Program A C source program is a collection of one or more directives declarations and statements contained in one or more source files statements Specify the action to be performed directives Instruct the preprocessor to act on the text of the program Pragma directives affect compiler behavior declarations Establish names and define linkage characteristics such as scope data type and linkage definitio
499. p function make sure the heap you specify is valid If the heap is not valid the behavior of the heap functions is undefined Adding to a Fixed Size Heap Although you created the heap with a fixed size you can add blocks of memory to it with uaddmem This can be useful if you have a large amount of memory that is allocated conditionally Like the starting block you must first allocate memory for a block of memory This block will be added to the current heap so make sure the block you add is the same type of memory as the heap you are adding it to For example to add 64K to fixedHeap static char newblock 65536 _uaddmem fixedHeap heap to add to newblock 65536 block to add _BLOCK_CLEAN sets memory to 0 Using _uaddmem is the only way to increase the size of a fixed heap Note For every block of memory you add a small number of bytes from it are used to store internal information To reduce the total amount of overhead it is better to add a few large blocks of memory than many small blocks Chapter 7 Writing C Programs 187 Destroying Your Heap When you have finished using the heap close it with uclose Once you have closed the heap in a process that process can no longer allocate from or return memory to that heap If other processes share the heap they can still use it until you close it in each of them Performing operations on a heap after you ve closed it causes undefined behavior To finally d
500. pec can only be the name of a file Notes When o is specified as part of a complier invocation file_spec can be the relative or absolute path name of either a directory or a file 1 If file_spec is the name of a directory files created by the compiler are placed into that directory 2 lf a directory with the name file_spec does not exist the o option specifies that the name of the file produced by the compiler will be file_spec Otherwise files created by the compiler will take on their default names For example the following compiler invocation xlc test c c 0 new o produces the object file new o instead of test o and xlc test c 0o new produces the object file new instead of a out A file_spec with a C source file suffix c or 1 such as my_text c or bob i results in an error and neither the compiler nor the linkage editor is invoked To use Fo on page 242 and o together you can only compile one source file at a time If you specify both c and ofile_spec and only one file is being compiled the output is placed in file_spec If more than one source file name is listed in the compiler invocation the compiler issues a warning message and ignores o The FE on page 253 and option options override the ofilename Example 1 To compile myprogram c so that the resulting file is called myaccount assuming that no directory with name myaccount exists enter xlc myprogram c o myaccount If the directo
501. piler error has been found This message should be reported to your IBM service representative The translator returns the following status codes for each severity level of diagnostic message Message Severity Return Code 3 The level of diagnostic can be controlled with the following compiler options 2 1 1 3 halt severity flag severityl severity2 g A for detailed information about C for AIX compiler diagnostic messages Related Reading Implementation Dependency Environment F 3 2 Program termination and library facilities are not available to a free standing program Only a hosted environment is available 2 1 2 1 Arguments passed to a C program from the AIX operating system command line can be retrieved as arguments of the function main 2 1 2 2 1 The first argument passed indicates the number of white space separated parameters supplied The second argument is an array of pointers to these parameters The third argument is a null terminated array of pointers to a set of system arguments for the program The arguments are traditionally named argc envp and argv but these names are not mandatory To access these variables the main function of your program must declare them as arguments The following table summarizes the main function arguments and their uses Name Meaning SSC pose int argc Argument count Contains the number of parameters supplied on the command line The name with which the
502. plete name starting from the root directory These path names start with the slash character The full path name locates the specified file regardless of the directory you are presently in called your working or current directory The following example specifies the full path to file mine h in John Doe s subdirectory example_prog u johndoe example_prog mine h Using a Relative Path Name to Imbed Files The relative path name locates a file relative to the directory that holds the current source file or relative to directories defined using the ldirectory option See AIX Version 4 System User s Guide Operating System and Devicesfor a complete explanation of the AIX file system Directory Search Sequence for Include Files Using Relative Path Names The C language defines two versions of the include preprocessor directive The C for AIX compiler supports both With the include directive you can search directories by enclosing the file name between lt gt or characters The result of using each method is as follows include type Directory Search Order include lt file_name gt If you specify the Idirectory option the compiler searches for file_name in the directory called directory first If more than one directory is specified the compiler searches the directories in the order that they appear on the command line Searches the directory usr include 178 C for AIX Users Guide include file_name
503. plus and minus infinity modes qopt Generates an assembly language file s for each source file flag noshowinc If used with the qsource option all the include files are included in the source listing qopt Specifies if and how parallelized object code is generated nosource Produces a compiler listing and includes source code spill 512 Specifies the size of the register allocation spill area nospnans Generates extra instructions to detect signalling NaN on conversion from single precision to double precision qopt nosmp qopt qopt qopt Adds the corresponding source code lines to the diagnostic messages in the stderr file qopt nosrcmsg 224 C for AIX User s Guide Kstatsym on page 324 qopt nostatsym Adds user defined non external names that have a persistent storage class to the name list qopt stdinc Specifies which files are included with include lt file_name gt and include file_name directives qopt See strict on page 324 Turns off aggressive optimizations that have the potential to alter the semantics of your program qopt Disables loop induction lbage 3271 variable optimizations that have the potential to alter the semantics of your program qopt Causes the compiler to perform syntax checking without generating an object file qopt nosuppress Lets you specify warning or information messages to be suppressed in the co
504. ponding undef directive the scope of the macro lasts until the end of the compilation is reached A recursive macro is not fully expanded For example the definition define x a b x a 1 b 1 4 would expand x 20 10 to x 20 1 10 1 4 rather than trying to expand the macro x over and over within itself A definition is not required to specify replacement tokens The following definition removes all instances of the token debug from subsequent lines in the current file define debug This is the same as specifying the Ddebug compiler option Note that specifying Ddebug without the equal sign gives the digit 1 as replacement text You can change the definition of a defined identifer or macro with a second preprocessor define directive only if the second preprocessor define statement is preceded by a preprocessor undef directive The undef directive nullifies the first definition so that the same identifier can be used in a redefinition Within the text of the program the preprocessor does not scan character constants or string constants for macro invocations Related Reading Example of the define Preprocessor Directive The following program contains two macro definitions and a macro invocation that refers to both of the defined macros aR xx This example illustrates define directives include lt stdio h gt define SQR s s s define PRNT a b printf value 1 d n a Appendix
505. possible The compiler can accurately analyze the use of local variables but it has to make several worst case assumptions about global Chapter 7 Writing C Programs 197 variables These assumptions tend to hinder optimization For example if you write a function that uses external variables heavily and that function also calls several external functions the compiler assumes that every call to an external function could change the value of every external variable If you know that none of the function calls affects the global variables that you are using and you have to read them frequently with function calls interspersed copy the global variables to local variables and then use these local variables The compiler can then perform optimization that it could not otherwise perform If you must use global variables use static variables with file scope rather than external variables wherever possible In a file with several related functions and static variables the optimizer can gather and use more information about how the variables are affected To access an external variable the compiler has to make an extra memory access to obtain the address of the variable When the compiler removes extraneous address loads it has to use a register to keep the address Using many external variables simultaneously takes up many registers Those that cannot fit into registers during optimization are spilled into memory Because all elements of an external st
506. pragma execution_frequency Preprocessor Directive eee ee ee eee ee eee 2 Or pragma hdrfile Preprocessor Directive 2 a eee ee ee ee ee 368 pragma hdrstop Preprocessor Directive 2 ee ee ee eee BBY pragma info Preprocessor Directive 2 2 ee eee ee ee eee BVO pragma isolated_call Preprocessor Directive 2 2 2 371 pragma langlvl Preprocessor Directive 1 ee ee ee ee ee ee 8B pragma leaves Preprocessor Directive 2 ee ee ee ee ee BB pragma map Preprocessor Directive coe wanes eee ke ee ee ee ee 2 ree pragma option_override Preprocessor Directive eee eee eee eke we ae ee ee Se Ore pragma options Preprocessor Directive 2 2 4 2 we ee ee ee BVH pragma reachable Preprocessor Directive 2 2 2 376 pragma strings Preprocessor Directive 0 0 eee ee ee ee 876 Preprocessor Macro Operators 1 we ee ee ee ee ew OTT Preprocessor Macro Operator 2 2 2 a ee ee ee ew OTT Preprocessor Macro Operator 1 a ee ee ee eee 878 Preprocessor Macro Operator 2 we ee ee ee ee ee BY Appendix E Parallel Processing Facilities eee ee ee eee es we Se 2 Ol pragma Preprocessor Directives for Parallel Processing cee ee et ee ee ee a eT pragma ibm critical Preprocessor Directive See eh a te eae ee ee ee ee pragma ibm independent_calls Preproce
507. priority for placement in machine registers The register storage class keyword Is required in a data definition and in a parameter declaration that describes an object having the register storage class An object having the register storage class specifier must be defined within a block or declared as a parameter to a function The following example lines define automatic storage duration objects using the register storage class specifier register int scorel 0 score 0 register unsigned char code A register int element amp order 0 Chapter 6 The C Language 111 Initialization You can initialize any register object except parameters If you do not initialize an automatic object its value is indeterminate If you provide an initial value the expression representing the initial value can be any valid C expression For structure and union members the initial value must be a valid constant expression if an initializer list is used The object is then set to that initial value each time the program block that contains the object s definition is entered Storage Objects with the register storage class specifier have automatic storage duration Each time a block is entered storage for register objects defined in that block are made available When the block is exited the objects are no longer available for use If a register object is defined within a function that is recursively invoked the memory is allocated for the vari
508. program A set of instructions written in a programming language that must be translated to machine language before the program can be run stanza A group of lines in a file that together have a common function or define a part of a system Stanzas are usually separated by blank lines or colons and each stanza has a name The stanzas of the C for AIX compiler default configuration file etc vac cfg specify information that the compiler uses when it is invoked statement An instruction that ends with a semicolon or one or more instructions enclosed in braces 496 C for AIX User s Guide static A keyword used for defining the scope and linkage of variables and functions For internal variables the variable has block scope and retains its value between function calls For external values the variable has file scope and retains its value within the source file For class variables the variable is shared by all objects of the class and retains its value within the entire program storage class specifier One of auto register static or extern string literal Zero or more characters enclosed in double quotation marks structure A data type that contains an ordered group of data objects Unlike an array the data objects within a structure can have varied data types structure tag The identifier that names a structure data type subscript One or more expressions each enclosed in brackets that follow an array name A subsc
509. prototype function definition can also have a list of parameter declarations which describe the types of parameters that the function receives In nonprototype functions parameters that are not declared have type int A function can be called by itself or by other functions Unless a function definition has the storage class specifier static the function also can be called by functions that appear in other files or modules Functions with a storage class specifier of static can only be directly invoked from within the same source file If a function has the storage class specifier static or a return type other than int the function definition or a declaration for the function must appear before and in the same file as a call to the function If a function definition has external linkage and a return type of int calls to the function can be made before it is visible because an implicit declaration of extern int func is assumed All declarations for a given function must be compatible that is the return type is the same and the parameters have the same type The default type for the return value and parameters of a function is int and the default storage class specifier is extern If the function does not return a value or it is not passed any parameters use the keyword void as the type specifier You can include ellipses at the end of your parameter list to indicate that a variable number of arguments will be passed to the functio
510. ption on the command line the first pragma options small directive encountered in the source file will override it e If you specify qenum small on the command line it is turned off by the first pragma options enum zint directive found in the source code e You cannot change the storage allocation of an enum using a pragma options enume within the declaration of an enum The following code segment generates a warning and the second occurrence of the enum option is ignored pragma options enum smal enum e_tag i as b pragma options enum int cannot be within a declaration C e var The range of enum constants must fall within the range of either unsigned int or int signed int For example the following code segments contain errors 256 C for AIX User s Guide pragma options enum smal enum e tag a 1 b 2147483648 larger than maximum int e var The enum constant range does not fit within the range of an int signed int pragma options enum smal enum e_tag a 0 b 4294967296 larger than maximum int e var The enum constant range does not fit within the range of an unsigned int pragma options enum smal enum e tag a 1 b 2147483647 max int C larger than maximum int e var The enum constant range does not fit within the range of an int signed int The pragma options keywords are ENUM SMALL to specify minimum sized ENUMS ENUME INT to disable minimum s
511. ptions Purpose Specifies various floating point options These options provide different strategies for soeeding up or improving the accuracy of floating point calculations Notes Using the float option may produce results that are not precisely the same as the default Incorrect results may be produced if not all required conditions are met For these reasons you should only use this option if you are experienced with floating point calculations involving IEEE floating point values and can properly assess the possibility of introducing errors in your program See before using this option The float option has the following suboptions lf you use more than one suboption separate each one with a colon qfloat emulate Emulates the floating point instructions omitted by the PowerPC 403 processor The default qfloat noemulate is float noemulate To emulate PowerPC 403 processor floating point instructions use qfloat emulate Function calls are emitted in place of PowerPC 403 floating point instructions Use this option only in a single threaded stand alone environment targeting the PowerPC 403 processor Do not use qfloat emulate with any of the following e qarch pwr qarch pwr2 qarch pwrx e qlongdouble qldbl128 e xlc128 compiler invocation command qfloat fltint Speeds up floating point to integer conversions by using faster inline code that does not qfloat nofltint check for overflows The default is float no
512. put output real 9 2 The following example defines an array of structures named records Each element of records contains three members the integer id_num the integer type of input and the union variable input which has the union data type defined in the previous example struct int id_num int type of input union data input records 10 The following statement assigns a character to the structure member input of the first element of records records 0 input charctr g Related Reading Incomplete Types Incomplete types are the type void an array of unknown size or structure union or enumeration tags that have no member lists For example the following are incomplete types void incomplete ptr struct dimension linear no previous definition of dimension void is an incomplete type that cannot be completed Incomplete structure or union and enumeration tags must be completed before being used to declare an object although you can define a pointer to an incomplete structure or union Related Reading auto The auto storage class specifier lets you define a variable with automatic storage its use and storage is restricted to the current block The storage class keyword auto is optional in a data declaration It is not permitted in a parameter declaration A variable having the auto storage class specifier must be declared within a block It cannot be used for file scope declarations Because a
513. quires parentheses b 1506 172 S Parameter type list for function add contains parameters without identifiers c 1506 172 S Parameter type list for function add contains parameters without identifiers The compiler also places messages in the source listing if you specify the qsource option If the qlanglvl option is set to ansi compile time messages about incorrect pragma directives are not generated You can conirol the diagnostic messages issued according to their severity using either the qflag option or the w option To get additional informational messages about potential problems in your program use the qinfo option Compiler Listings The listings produced by the compiler are a useful debugging aid By specifying appropriate options you can request information on all aspects of a compilation The listing consists of a combination of the following sections e Header section that lists the compiler name version and release as well as the source file name and the date and time of the compilation e Source section that lists the input source code with line numbers e Options section that lists the options that were in effect during the compilation e Attribute and cross reference listing section that provides information about the variables used in the compilation unit e File table section that shows the file number and file name for each main source file and include file e Compilation epilogue section that summa
514. r AIX Users Guide Appendix G Built in Functions for PowerPC Processors PowerPC platforms support certain RS 6000 machine instructions not available on other platforms If performance is critical to your application the C for AIX compiler provides a set of built in functions that directly map to certain RS 6000 instructions By using these functions function call return costs parameter passing stack adjustment and all the additional costs related with function invocations are eliminated Not all functions described below are supported by all RS 6000 processors Using an unsupported function will result in an error message being displayed Name __fmadds __fmadd __fmsubs __fmsub __fnmadds __fnmadd __fnmsubs __fnmsub __fsqrts __fsqrt __frsqrte _ fres _ fsels _ fsel _ fabss _ fabs __fnabss __fnabs __ debt __dcbz __trap Copyright IBM Corp 1995 1999 Prototype float __fmadds float float float double __fmadd double double double float __fmsubs float float float double __fmsub double double double float __fnmadds float float float double __fnmadd double double double float __fnmsubs float float float double __fnmsub double double double float __fsqrts float double __fsqrt double double __frsaqrte double float __fres float float _fsels float float float double __fsel
515. r an array of num elements each of length size bytes It then initializes all bits of each element to O In addition _debug_ucalloc makes an implicit call to _uheap_check and stores the name of the file file and the line number line where the storage is allocated This information can be used later by the _uheap_check _uheap_allocated or udump_allocated_delta functions To use _debug_ucalloc you must compile with the debug memory qheapdebug compiler option This option maps all _ucalloc calls to debug_ucalloc Note The qheapdebug option maps all calls to memory management functions including heap specific versions to their debug counterparts To prevent a call from being mapped parenthesize the function name _debug_ucalloc works just like _debug_calloc except that you specify the heap to use debug _calloc always allocates from the default heap If the heap does not have enough memory for the request debug _ucalloc calls the getmore_fn that you specified when you created the heap with _ucreate To reallocate or free memory allocated with _debug_ucalloc use the non heap specific _debug_realloc and debug_free These functions always check what heap the memory was allocated from 428 C for AIX Users Guide Return Value _debug_ucalloc returns a pointer to the reserved space If size or num was specified as zero or if your getmore_fn cannot provide enough memory _debug_ucalloc returns NULL Passing _debug_ucalloc a heap that is
516. r consists of an identifier which names a data object For example the following block scope data declaration uses initial as the declarator auto char initial The data object initial has the storage class auto and the data type char The following table describes some more declarators Example int owner int node int names 126 int action volatile int min int volatile volume volatile int next volatile int sequence 5 extern const volatile int op system clock Related Reading 64 C for AIX User s Guide Description owner is an int object node is a pointer to an int data object names is an array of 126 int elements action is a function returning a pointer to an int min is an int that has the volatile qualifier volume is a volatile pointer to an int next is a pointer to a volatile int sequence is an array of five pointers to volatile int objects op system clock is a constant and volatile int with static storage duration and external linkage Storage Class Specifiers The storage class specifier used within the declaration determines whether e The object has internal external or no linkage e The object is to be stored in memory or in a register if available e The object receives the default initial value 0 or an indeterminate default initial value e The object can be referenced throughout a program or only within the function block or source file where the variable is defined
517. r has an external name which is the same as the function name but without a leading dot This descriptor name is used in all import and export operations 212 C for AIX User s Guide Related Reading Interlanguage Calls Function Return Values Functions pass their return values according to type e Pointers enumerated types and integral values int short long char and unsigned types of any length are returned right justified in R3 long long values are returned in R3 and R4 e floats and doubles are returned in FP1 128 bit long doubles are returned in FP1 and FP2 e Calling functions supply a pointer to a memory location where the called function stores the returned value e long doubles are returned in R1 and R2 Related Reading Interlanguage Calls Stack Floor The stack floor is a system defined address below which the stack cannot grow All programs in the system must avoid accessing locations in the stack segment that are below the stack floor Other system invariants related to the stack must be maintained by all compilers and assemblers e No data is saved or accessed from an address lower than the stack floor e The stack pointer is always valid When the stack frame size is more than 32767 bytes take care to ensure that its value is changed in a single instruction so that there is no timing window in which a signal handler would either overlay the stack data or erroneously appear to overflow the
518. r thread in the program is executing a critical region with that same name Critical sections not specifically named by the ibm critical or omp critical directives are mapped to the same unspecified name Related Reading pragma ibm independent_calls Preprocessor Directive The independent_calls pragma asserts that specified function calls within the chosen loop have no loop carried dependencies This information helps the compiler perform dependency analysis Syntax pragma ibm independent_calls identifier identifier lt countable for while do loop gt where identifier represents the name of a function Notes identifier cannot be the name of a pointer to a function If no function identifiers are specified the compiler assumes that all functions inside the loop are free of carried dependencies Example pragma ibm independent calls int s a 100 i N 100 int foo int pragma ibm independent_calls foo for i 0 i lt N i ali foo i Related Reading Appendix E Parallel Processing Facilities 383 pragma ibm independent_loop Preprocessor Directive The independent_loop pragma asserts that iterations of the chosen loop are independent and that the loop can be parallelized Syntax pragma ibm independent_loop Lif exp lt countable for while do loop gt where exp represents a scalar expression When the if argument is specified loop iterations are considered indep
519. rage long long int Allocates 4 bytes of data storage in 32 bit mode 8 bytes in 64 bit mode long long long long int Allocates 8 bytes of data storage The C compiler supports long long but this is not a standard C data type Though needed for some AIX system programming it may not be portable to other systems Notes The amount of storage allocated for an int short or long integer variable is implementation dependent To declare a data object having an integer data type use an int type specifier The int specifier has the form The declarator for a simple integer definition or declaration is an identifier You can initialize a simple integer definition with an integer constant or with an expression that evaluates to a value that can be assigned to an integer The storage class of a variable determines how you can initialize the variable The unsigned prefix indicates that the object is a nonnegative integer Each unsigned type provides the same size storage as its signed equivalent For example int reserves the same storage as unsigned int Because a signed type reserves a sign bit an unsigned type can hold a larger positive integer than the equivalent signed type The following example defines the short int variable flag Short int flag The following example defines the int variable result int result Chapter 6 The C Language 81 The following example defines the unsigned long int variable ss_number as having t
520. rary function 4 9 10 4 456 C for AIX User s Guide The error message includes the name of the program that caused the error followed by a colon a blank the message string and a new line character The error number is taken from the global variable errno which is set when an error occurs but is not cleared when a successful call is made The following table lists the content of the error message strings Error Number Message Text Error Number Message Text O o woema S Mising le or Mie stom No such device oradress se Destination address required O __ Exectormatewor so Protocol wong type for socket o bamen n Poboonotavaae me u a Protocol family not supported Protocol family not supported not supported Bad address MEAN kaoi in Address not supported by protocol family eee a a a S C Nospaceiet ondevie o rasom CO a eoo o Fienamerobng Appendix Implementation Dependencies Overview 457 Message Text Error Number Message Text a ta wa ar Chane number out orange 98 hemis notiocaltonost a SS Ma No CSI structure available 114 Not a Trusted Program Too many references can t splice ee a a CE eee eee No locks available locks available 12000 Error in protocol in Error in protocol cI eina Cannot Establish Connection No message on stream head read queue Connection Down Down fd not associated with a stream _ not as
521. ration Considerations This section outlines various portability considerations in moving C programs from 32 bit to 64 bit mode Constants page B41 e Undeclared Functions page B42 e Assignment of Long Types to Integer and Pointers page B42 e Structure Sizes and Alignment page B43 Bitfields page B43 e Miscellaneous page B43 e Interlanguage Calls with Fortran page B44 Constants The limits of constants change This table shows changed items in the limits h header file their hexadecimal value and decimal equivalent The equation gives an idea of how to construct these values OO e Hexadecimal Eaton Decima signed long min 0x8000000000000000L 263 9 223 372 036 854 775 808 LONG_MIN E 0x7 FFFFFFFFFFFFFFFL 263_1 9 223 372 036 854 775 807 Ne LONG MIN 1 unsigned long max 9xFFFFFFFFFFFFFFFFUL 2644 18 446 744 073 709 551 616 ULONG_MAX In C type identification of constants follows explicit rules However programs that use constants exceeding the limit relying on a 2 s complement representation will experience unexpected results in the 64 bit mode This is especially true of hexadecimal constants and unsuffixed constants which are more likely to be extended into the 64 bit long type Problematic behaviors will generally occur at boundary areas such as e constant gt UINT MAX e constant lt INT MIN e constant gt INT MAX Some examples of undesirable boundary side effects are C
522. rched for by the linkage editor This option remains in effect until overridden by the appearance of the bdynamic option which in turn affects Ikey options appearing after it The default option bdynamic ensures that the C library lib c links dynamically To avoid possible problems with unresolved linker errors when linking the C library you must add the bdynamic option to the end of any compilation sections that use the bstatic option Example To compile myprogram c using a static version of the libtask a Task Library and a dynamic version version of the libcomplex aComplex Mathematics Library enter xlc myprogram c bstatic Itask bdynamic lcomplex Related Reading Appendix A Compiler Options 241 C Option Type Default Value pragma options e Syntax C Purpose Preserves comments in preprocessed output Notes The C option has no effect without either the E or the P option With the E option comments are written to standard output With the P option comments are written to an output file Example To compile myprogram c to produce a file myprogram i that contains the preprocessed program text including comments enter xlc myprogram c P C Related Reading Option Type Default Value pragma options e Syntax C Purpose Instructs the compiler to pass source files to the compiler only Notes The compiled source files are not sent to the linkage editor The compiler creates an output obj
523. rder bit becomes sign bit unsigned int Preserve Preserve Preserve bit Preserve bit Zero extend low order bytes low order bytes pattern pattern high order bit high order bit becomes sign bit becomes sign bit unsigned long Preserve Preserve Preserve bit Preserve bit Zero extend low order bytes low order bytes pattern pattern high order bit high order bit becomes sign bit becomes sign bit unsigned long Preserve Preserve Preserve Preserve Preserve bit long low order bytes low order bytes low order bytes low order bytes pattern high order bit becomes sign bit signed long Convert to int Convert to int Truncate at Truncate at Truncate at and convert int to and convert int to decimal if result decimal if result decimal if result signed char signed short is too large for is too large for is too large for int result is long result is long long result undefined undefined is undefined Appendix Implementation Dependencies Overview 461 Convert to int and convert int to signed char Convert to int and convert int to signed char long double Convert to int and convert int to signed short Convert to int and convert int to signed short Type Conversions Unsigned Integer Types Truncate at decimal if result is too large for int result is undefined Truncate at decimal if result is too large for int result is undefined Truncate at decimal if result is too large for long result is und
524. re described in the AIX Version 4 Files Reference Each multibyte character can contain up to 4 bytes To represent the single quotation symbol backslash and new line characters you must use the rr escape sequence For more information on escape sequences see The following are examples of character constants a Q y T a A e Am 117 50 C for AIX Users Guide Notes 1 In extended mode a character constant longer than 2 characters causes a warning to be issued by the C compiler Only the rightmost 4 characters are used A character constant with 4 characters has an unsigned int value 2 In ansi mode a character constant longer than 1 character causes a warning to be issued Only the rightmost 4 characters are used For example the character constant too _long causes the following message 1506 076 W Character constant has more than one character Rightmost four characters are used String Literals A string constant or literal contains a sequence of characters or escape sequences enclosed in double quotation mark symbols gt i A z ee I character Scape oecence The prefix L indicates a wide character string literal A null 0 character is appended to each string For a wide character string a string prefixed by the letter L the value 0 of type wchar_t is appended By convention programs recognize the end of a string by finding the null character Multiple spaces contained withi
525. re static extern and typedef If you specify static all variables defined in it have internal linkage If you do not specify static all variables defined in it have external linkage If you specify the storage class you can omit the type specifier If you omit the type specifier all variables defined in that declaration receive the type int Initialization You can initialize any object with file scope If you do not initialize a file scope variable its initial value is zero of the appropriate type If you do initialize it the initializer must be described by a constant expression or it must reduce to the address of a previously declared variable at file scope possibly modified by a constant expression Initialization of all variables at file scope takes place before the main function begins running Storage All objects with file scope data declarations have static storage duration Storage is allocated at runtime and freed when the program stops running Related Reading Chapter 6 The C Language 63 Declarators A declarator designates a data object or function Declarators appear in all data definitions and declarations and in some type definitions identifier subscript deciarat porameter tyne fist a rn ea You cannot declare or define a volatile or const function A subscript declarator describes the number of dimensions in an array and the number of elements in each dimension A simple declarato
526. readprivate list where ist is a comma separated list of variables Notes Each copy of an omp threadprivate data variable is initialized once prior to first use of that copy If an object is changed before being used to initialize a threadprivate data variable behavior is unspecified A thread must not reference another thread s copy of an omp threadprivate data variable References will always be to the master thread s copy of the data variable when executing serial and master regions of the program Use of the omp threadprivate directive is governed by the following points e An omp threadprivate directive must appear at file scope outside of any definition or declaration Appendix E Parallel Processing Facilities 399 e A data variable must be declared with file scope prior to inclusion in an omp threadprivate directive ist e An omp threadprivate directive and its ist must lexically precede any reference to a data variable found in that list e A data variable specified in an omp threadprivate directive in one translation unit must also be specified as such in all other translation units in which it is declared e Data variables specified in an omp threadprivate ist must not appear in any clause other than the copyin schedule and if clauses e The address of a data variable in an omp threadprivate st is not an address constant e A data variable specified in an omp threadprivate ist must not have an incomplete or referen
527. referred to as the identifiers scope The scope of an identifier is determined by where the identifier is declared The four kinds of scope and their descriptions are Chapter 6 The C Language 53 Block Scope The identifiers declaration is located inside a statement block A block starts with an opening brace and ends with a closing brace An identifier with block scope is visible between the point where it is declared and the closing brace that ends the block Block scope is sometimes referred to as local scope Function Scope The only identifier with function scope is a label name A label is implicitly declared by its appearance in the program source A goto statement transfers control to the label specified in the goto statement The label is visible to any goto statement that appears in the same function as the label File Scope The identifer s declaration appears outside any block lt is visible from the point where it is declared to the end of the source file If the source files are included by include preprocessor directives those files are considered to be part of the source and the identifier will be visible to all included files that appear after the declaration of the identifier The identifier can be declared again as a block scope variable The new declaration replaces the file scope declaration until the end of the block Function Prototype Scope The identifiers declaration appears within the list of parameter
528. reprocessor directive is to be ignored the tokens are examined only to identify preprocessor directives within that block so that the conditional nesting level can be determined All tokens other than the name of the directive are ignored Only the first block whose expression is nonzero is processed The remaining blocks at that nesting level are ignored If none of the blocks at that nesting level has been processed and there is a else directive 60 C for AIX User s Guide the block following the else directive is processed If none of the blocks at that nesting level has been processed and there is no else directive the entire nesting level is ignored Related Reading Declarations Overview A declaration establishes the names and characteristics of data objects and functions used in a program A definition allocates storage for data objects or specifies the body for a function When you define a type no storage is allocated Declarations determine the following properties of data objects and their identifiers e Scope which describes the visibility of an identifier in a block or source file e Linkage which describes the association between two identical identifiers e Storage duration which describes when the system allocates and frees storage for a data object e Type which describes the kind of data the object is to represent foe soeeifier storage class specifier fyoe specifier pY edaran m pa initializer
529. requires to this value to determine the size of the block you need to get Also make sure the block is the correct type regular or shared for the heap you are creating After you have allocated a block of memory create the heap with ucreate For example Heap _t fixedHeap this is the heap handle get memory for internal info plus 5000 bytes for the heap static char block _HEAP MIN SIZE 5000 fixedHeap _ucreate block _HEAP MIN SIZE 5000 block to use BLOCK CLEAN memory is not set to Q _HEAP_REGULAR regular memory NULL NULL we ll explain this later The BLOCK_CLEAN parameter indicates that the memory in the block has not been initialized to O If it were set to O for example by memset you would specify BLOCK CLEAN The calloc and _ucalloc functions use this information to improve their efficiency if the memory is already initialized to 0 they don t need to initialize it The fourth parameter indicates what type of memory the heap contains regular HEAP REGULAR or shared _ HEAP_SHARED The different memory types are described in z For a fixed size heap the last two parameters are always NULL Using Your Heap Once you have created your heap you can open it for use by calling _uopen _uopen fixedHeap This opens the heap for that particular process if the heap is shared each process that uses the heap needs its own call to _uopen 186 C for AIX User s Guide
530. res of extended level C that conflict with either RT C or ANSI ISO C Features that are part of extended C but not part of RT C are not listed in the table unless they present a conflict asm and fortran keywords Supported Not Supported Not Supported and operator Supported Not Supported Not Supported Type specifier not required Supported Not Supported Not Supported when a name that was previously defined as a typedef is redefined Scope of external data File Block Block declared or defined at block scope ifdef using logical Supported Not Supported Not Supported operators or period Taking the address of a Supported Not Supported Not Supported register variable Modifiable or unmodifiable Modifiable Unmodifiable Modifiable String literals Relaxed ref def model Supported Not Supported Supported unsigned char and Supported Not Supported Changed to unsigned int unsigned short bit fields unsigned char and char Not Supported Supported Not Supported recognized as incompatible types long long int type Not Supported Not Supported Supported Scope of external functions File Block File declared at block scope Handling of macro Expanded Not Expanded Expanded parameters within string literals Preprocessor macro can be Supported Not Supported Supported redefined without first being undefined Rules followed when RTC ANSI ISO RTC performing arithmetic conversions All valid pointer conversions Supported Not Supported Supporte
531. ression t is evaluated only before the statement is processed for the first time You can use this expression to initialize a variable If you do not want to evaluate an expression prior to the first iteration of the statement you can omit this expression expression2 Is the controlling part It is evaluated before each iteration of the statement It must evaluate to a scalar type If it evaluates to 0 zero the statement is not processed and control moves to the next statement following the for statement If exoression2 does not evaluate to 0 the statement is processed If you omit expression2 it is as if the expression had been replaced by a nonzero constant and the for statement is not terminated by failure of this condition expression3 Is evaluated after each iteration of the statement You can use this expression to increase decrease or reinitialize a variable This expression is optional A break return or goto statement can cause a for statement to end even when the second expression does not evaluate to 0 If you omit expression2 you must use a break return or goto statement to end the for statement Related Reading Examples Using the for Statement The following for statement prints the value of count 20 times The for statement initially sets the value of count to 1 After each iteration of the statement count is incremented for count 1 count lt 20 count printf count d n count The following
532. rgument For the following source code fragment define mm aa aa int a int b mm This is a C comment int blah int C This is a C comment int d The output for the P option int a int b int blah int C int d The output for the P C options int a int b int blah int c This is a C comment int d The output for the E option is line 1 fred c int a int b int blah int C int d The output for the E C option is line 1 fred c int a int D Appendix A Compiler Options 249 int blah int C This is a C comment int d A comment may contain a sequence of valid multibyte characters The character sequence begins a C comment except within a header name a character constant a string literal or a comment The character sequence or and are ignored within a C comment Comments do not nest Macro replacement is not performed within comments Compile Example To compile myprogram c so that C comments are recognized as comments enter xlc myprogram c qcpluscmt Related Reading Option Type Default Value pragma options e Syntax Dname definition Dname Dname Purpose Defines the identifier name as in a define preprocessor directive definition is an optional definition or value assigned to name Notes The identifier name can also be defined in your source program using the define preprocessor directive Dname is equiva
533. rictions The floating point rounding mode can only be changed at the beginning and end of a function It cannot be changed across a function call and if it is changed within a function it must be restored before returning to the calling routine Related Reading Creating and Using Precompiled Headers You can improve your compile time by using precompiled headers Use the qgenpcomp and qusepcomp compiler options to create and maintain precompiled header files for your application If you use these two options consistently a precompiled header file is created if it does not exist and used if it does exist When a source file is changed the precompiled version is automatically regenerated The compiler generates a single precompiled object for the first initial sequence of include directives The next time you compile this single object can be used wherever that initial sequence appears Since the precompiled object is only used in cases where the context is the same same language same beginning sequence of include directives compatible options and macro definitions the precompiled object does not have to be reinterpreted every time it is included Chapter 4 Advanced Compiler Usage 35 To get the most benefit from this new method use the same initial sequence of headers wherever possible The more files that share the same initial sequence the greater the improvement in your compile time You can specify different names or
534. ries 4 while INPUT READY Wait for input temp INPUT BUF __ijiospace eieio synchronize the 1 0 if temp 0 return count while OUTPUT READY Wait for output x QUTPUT BUF temp __ijiospace eieio synchronize the 1 0 COUNT TT __jiospace sync synchronize the CPU for count to allow other CPUs to access it x Related Reading 466 C for AIX User s Guide Appendix J C for AIX and XL C Compatibility This appendix discusses compatibility issues between the C for AIX compiler and the XL C compiler The C for AIX compiler is not fully compatible with XL C it is a stricter compiler than XL C The following are the differences 1 C for AIX implements tighter ANSI conformance For example the following code segments are accepted by XL C but not by C for AIX Example 1 Mixing K amp R style and ANSI style function prototypes void func void func float f Accepting this code leads to runtime problems since the float parameter in the definition is first promoted to double default argument promotions When the float argument is passed in the wrong size registers are taken off the stack Example 2 Null dimension multi dimensional arrays Arrays of incomplete arrays are not allowed not even on parameters void f int p All dimensions except the first must be specified for a multi dimensional array In the above example p is defined to be an incomple
535. ript refers to an element in an array switch expression The controlling expression of a switch statement switch statement A C language statement that causes control to be transferred to one of several statements depending on the value of an expression 7 token The smallest independent unit of meaning of a program as defined either by a parser or a lexical analyzer A token can contain data a language keyword an identifier or other parts of language syntax translation The process of transforming all or part of a source program into into a program image that contains all the information needed for the program to run type The description of the data and the operations that can be performed on or by the data type balancing A conversion that makes both operands have the same data type If the operands do not have the same size data type the compiler converts the value of the operand with the smaller type to a value having the larger type type conversion See kad type definition A definition of a data type type specifier Used to indicate the data type of an object or function being declared U ultimate consumer The target of data in an input and output operation An ultimate consumer can be a file a device or an array of bytes in memory Appendix O Glossary 497 ultimate producer The source of data in an input and output operation An ultimate producer can be a file a device or an array of bytes in memory
536. rizes the diagnostic messages lists the number of source lines read and indicates whether the compilation was successful e Object section that is produced only when the list option is in effect and that lists the object code Each section except the header section has a section heading that identifies it The section heading is enclosed by angle brackets Related Reading Chapter 3 Using the C for AIX Compiler 19 Message Severity Levels and Compiler Response The following table shows the compiler response associated with each level of message severity Informational Compilation continues The message reports conditions found during compilation W Warning Compilation continues The message reports valid but possibly unintended conditions Error Compilation continues and object code is generated Error conditions exist that the compiler can correct but the program might not run correctly Severe error Compilation continues but object code is not generated Error conditions exist that the compiler cannot correct Unrecoverable error The compiler halts An internal compiler error has been found This message should be reported to your IBM service representative Related Reading E S U Compiler Return Codes At the end of compilation the compiler sets the return code to zero under any of the following conditions e No messages are issued e The highest severity level of all errors diagnosed is E W or l
537. rmation of object 0x00073890 was overwritten at 0x0007388c The first eight bytes of the memory block in hex are AAAAAAAAAAAAAAAA This memory block was re allocated at line number 8 in debug mallo c Heap state was valid at line 8 of debug mallo c Memory error detected at line 13 of debug mallo c KK KKK KKK KKK KERR ERK ER KEK RRR KERR RRR RE KK KR ERK KERR KER KER KER ERK ER KK ERERERERERER Related Reading _debug_memcpy Copy Bytes Format include lt string h gt void debug _memcpy void dest const void src size_t count const char file size t line Language Level Extension _debug_memcpy is the debug version of memcpy Like memcpy it copies count bytes of src to dest where the behavior is undefined if copying takes place between objects that overlap _debug_memcpy validates the heap after copying the bytes to the target location and performs this check only when the target is within a heap debug memcpy makes an implicit call to heap check If _debug_memcpy detects a corrupted heap when it makes a call to heap check debug memcpy will report the file name file and line number line in a message Note debug memcpy checks only the current default heap Therefore this debug support will not check all heaps within applications that have multiple user heaps To use debug memcpy you must compile with the debug memory qheapdebug compiler option This option maps all memcpy calls to debug memcpy You do not hav
538. rn memory to system CloseHandle hFile return 0 main Main function to test creating writing to and destroying a shared heap int main void int ve 13 for return code loop iteration Heap _t uheap oldheap heap to create old default heap char p for allocating from the heap Get the heap storage from the shared memory uheap inithp if uheap NULL return 1 Register uheap as default runtime heap save old default oldheap _udefault uheap 194 C for AIX Users Guide x x if oldheap NULL return termhp uheap Perform operations on uheap for i 1 i lt 5 i p malloc 10 malloc uses default heap which is now uheap memset p M _msize p Replace original default heap and check result if uheap udefault oldheap return termhp uheap Close my views of the heap rc termhp uheap ifdef DEBUG printf Returning from memshr2 rc d n rc endif return rc Related Reading Debugging Programs with Heap Memory C for AIX provides debug versions of both general memory management functions and heap specific memory management functions To automatically call the debug versions of these functions specify the qheapdebug compiler option when compil
539. rning message issued These suboptions are e auto e nested_par e rec_locks e schedule affinity n Specifies whether recursive locks are used to implement critical sections lf rec_locks is in effect recursive locks are used and nested critical sections will not cause a deadlock The default is norec_locks or regular locks Specifies what kind of scheduling algorithms and chunking are used for loops to which no other scheduling algorithm has been explicitly assigned in the source code Valid options for sched_type are e dynamic n e guided n e static n e affinity n e runtime If sched_type is not specified runtime is assumed as the default setting For more information about these scheduling algorithms see schedule pragma Appendix A Compiler Options 321 e Specifying qsmp without suboptions is equivalent to specifying qsmp auto explicit noomp norec_locks nonested_par schedule runtime e The qnosmp default option setting specifies that no code should be generated for parallelization directives though syntax checking will still be performed Use qignprag omp ibm to completely ignore parallelization directives e Specifying qsmp defines the _IBMSMP preprocessing macro e Specifying qsmp implicitly sets O2 The qsmp option overrides qnooptimize but does not override O3 or O4 e qsmp must be used only with thread safe compiler mode invocations such as xlc_r These invocations ensure that the pthrea
540. rofiled L usr lib profiled Appendix L C for AIX Files 475 hdlibs L usr vac lib lhmd_r options qgansialias qldbl128 qthreaded D THREAD SAFE D_VACPP MULTI _ C compiler extended mode cc128 r use DEFLT crt lib crt0_r o mert lib mcrt0 r o gcrt lib gcrt0 r o libraries L usr lib threads 1lpthreads 1c128 r 1c128 1lc_r usr lib libc a proflibs L lib profiled L usr lib profiled hdlibs L usr vac lib lhmd_r options qlanglvl extended qnoro qnoroconst qldbl128 qthreaded D THREAD SAFE D_VACPP_MULTI _ x x1C C compiler aliased as x1C_r AIX Threads XC re use DEFLT crt usr vacpp lib crt0 r o mcrt usr vacpp lib mcrt0_r o gcrt usr vacpp lib gcrt0_r o options qansialias qthreaded D THREAD SAFE D_VACPP_MULTI _ libraries2 L usr lib threads L usr vacpp 1lib 1C_r 1C lpthreads lc_r lm usr lib libc a proflibs L usr vacpp 1lib profiled L lib profiled L usr 1lib profiled hdlibs L usr vac lib IhC_r lhmd_r x C compiler with 128 bit long double AIX Threads x1C128 r use DEFLT crt usr vacpp lib crt0 r o mert usr vacpp lib mcrt0_r o gcrt usr vacpp lib gcrt0_r o libraries2 L usr lib threads L usr vacpp lib 1C128 r 1C128 1C_r 1C lpthreads 1c128 r 1c128 lc_r 1lm us proflibs L usr vacpp 1lib profiled L lib profiled L usr lib profiled hdlibs L usr vac lib IhC_r lhmd_r options qgansialias qldbl128 qthreaded D THREAD SAFE D_VACPP MULTI _ x Stan
541. rogramming practices that can work by accident without aggressive optimization but are exposed with IPA a Relying on the allocation order or location of automatics For example taking the address of an automatic variable and then later comparing it with the address of another local to determine the growth direction of a stack The C language does not guarantee where an automatic variable is allocated or it s position relative to other automatics Do not compile such a function with IPA and expect it to work b Accessing either an invalid pointer or beyond an array s bounds IPA can reorganize global data structures A wayward pointer which may have previously modified unused memory may now trample upon user allocated storage Ensure you have sufficient resources to compile with IPA IPA can generate significantly larger object files than traditional compilers As a result the temporary storage used to hold these intermediate files by convention tmp on AIX is sometimes too small If a large application is being compiled consider redirecting temporary storage with the TMPDIR environment variable Ensure there is enough swap space to run IPA at least 200Mb for large programs Otherwise the operating system might kill IPA with a signal 9 which cannot be trapped and IPA will be unable to clean up its temporary files Appendix A Compiler Options 283 6 You can link objects created with different releases of the compiler but you
542. rpose preprocessing No assumptions are made concerning the input or the intended use of the output This mode is intended for use with input files that are not written in C As such all preprocessor specific constructs are processed as described in the ANSI C standard In this case the continuation sequence is removed as described in the Phases of Translation of that standard All non preprocessor specific text should be output as it appears Using E causes line directives to be generated to preserve the source coordinates of the tokens Blank lines are stripped and replaced by compensating line directives The line continuation sequence is removed and the source lines are concatenated with the P option With the E option the tokens are output on separate lines in order to preserve the source coordinates The continuation sequence may be removed in this case The E option overrides the P o and qsyntaxonly options and accepts any file name If used with the M option E will work only for files with a c C source files or a i preprocessed source files filename suffix Source files with unrecognized filename suffixes are treated and preprocessed as C files and no error message Is generated Comments are replaced in the preprocessed output by a single space character New lines and line directives are issued for comments that span multiple source lines and when C is not specified Comments within a macro function argumen
543. rs at line 18 To avoid commenting over comments already in the source code you can use conditional compilation preprocessor directives to cause the compiler to bypass sections of a C program For example one method to ignore lines 15 through 17 would be to change line 14 to 14 if 0 and line 18 to 18 endif To later reenable the ignored comments change line 14 to 14 if 1 46 Cor AIX Users Guide Conditional compilation preprocessor directives are described in Preprocessor Directives Related Reading Identifiers Identifiers consist of an arbitrary number of letters or digits They provide names for the following language elements e Functions e Data objects e Labels e Tags e Parameters e Macros e Typedefs e Structure and union members There is no limit for the number of characters in an identifier However the linkage editor does limit the number of significant characters in external identifiers and truncates them after 4095 characters The compiler distinguishes between uppercase and lowercase letters in identifiers For example PROFIT and profit represent different data objects Note The underscore character _ is considered a letter In ansi mode identifiers can begin with _ but not with In extended mode identifiers can begin with _ or but you should avoid using these characters at the beginning of identifiers because they are reserved for internal system names The j compiler option
544. rst definition is a string literal and the second is a character constant DMYMACRO kpsmultibyte_chardcs DMYMACRO multibyte_char The qmbcs compiler option permits both double byte and multibyte characters In other respects it is equivalent to the qdbcs option but it should be used when multibyte characters appear in the program The listings produced by the qlist and qsource options display the date and time for the appropriate international language Multibyte characters in the file name of the C source file also appear in the name of the corresponding list file For example a C source file called multibyte char c gives a list file called 470 C for AIX Users Guide multibyte char Ist File Names and Comments Any file name can contain multibyte characters The file name can be a relative or absolute path name For example include lt multibyte char mydir mysource multibyte_ char h gt include multibyte char h xlc u myhome c_programs kanji_files multibyte char c omultibyte char Multibyte characters are also permitted in comments if you specify the qmbcs compiler option Comments are described in AlX Version 4 Language Reference Restrictions Multibyte characters are not permitted in identifiers Hexadecimal values for multibyte characters must be in the range of the code page being used You cannot mix wide characters and multibyte characters in macro definitions For example a macro expansion th
545. rt0 o l1ib mcrt0 o lib gcrt0 o L usr lib threads ldcelibc_r ldcepthreads lpthreads compat Ipthreads 1c128 1c L lib profiled L usr lib profiled Appendix L C for AIX Files 479 hdlibs options L usr vac 1lib 1hmd qlanglvl extended qnoro qnoroconst qthreaded D THREAD SAFE D_VACPP MULTI D AIX PTHREADS D 7 x x1C C compiler aliased as x1C_r4 DCE xIC_r4 use Crt mcrt 7 gcrt libraries2 proflibs hdlibs options DEFLT lib crt o 1ib mcrt o lib gcrt0 o L usr lib threads L usr vacpp lib 1C ldcelibc r ldcepthreads Ipthreads compat Ipthreads 1m lc L usr vacpp 1lib profiled L lib profiled L usr 1lib profiled L usr vac 1ib 1hC 1hmd qgansialias qthreaded D THREAD SAFE D VACPP MULTI D AIX PTHREADS D7 D AIX32_THREADS 1 D AIX41 x1C C compiler with 128 bit long double aliased as x1C128 _ r4 DCE x1C128 r4 use Crt mcrt gcrt libraries2 proflibs hdlibs options Standard c gampi ier xlc_r 7 use Crt mcert gcrt libraries proflibs hdlibs options Xlcl26 r7 Use crt mcrt gcrt libraries proflibs hdlibs options standard c compiler cc_r use crt mcert gcrt libraries proflibs hdlibs options cc128 r7 use crt mcert gorr libraries proflibs hdlibs options DEFLT Ab ero lib mcrt0 o lib gcrt0 o L usr 1lib threads L usr vacpp 1ib 1C128 1C ldcelibc_r ldcepthreads lpthreads_ compat 1m Ipthre L usr
546. rt0 o libraries 1c128 lc proflibs L lib profiled L usr 1lib profiled options qlanglvl extended qnoro qnoroconst qldb1128 Strict ANSI Compi Ler ANSI headers c89 use DEFLT crt lib crt0 o mcrt lib mcrt0 o gcrt lib gcrt0 o libraries lc proflibs L lib profiled L usr lib profiled options D ANSI C_ SOURCE qansialias qnolonglong qstrict induction C compiler xIC2 use DEFLT ert lib crt0 o mert 1ib mcrt0 o gcrt lib gcrt0 o libraries2 L usr vacpp lib 1C Im lpthreads 1c proflibs L usr vacpp lib profiled L lib profiled L usr lib profiled hdlibs L usr vac 1ib 1hC 1hmd options qansialias C compiler with 128 bit long double x1C128 use DEFLT crt lib crt0 o mcrt lib mcrt0 o gcrt lib gcrt0 o libraries2 L usr vacpp 1ib 1C128 1C Im Ipthreads 1c128 1c proflibs L usr vacpp 1lib profiled L lib profiled L usr 1ib profiled hdlibs L usr vac 1ib 1hC 1hmd options qgansialias qldb1128 standard c compi ler aliased as xlc_r AIX Threads xle rs use DEFLT crt lib crt0 o mert 1ib mcrt0 o gcrt lib gcrt0 o libraries L usr lib threads lpthreads 1c proflibs L lib profiled L usr lib profiled hdlibs L usr vac lib 1lhmd options qansialias qthreaded D THREAD SAFE D VACPP MULTI _ x xl c128 r xlc128_r use DEFLI crt lib crt0 o mert 1ib mcrt0 o gcrt lib gcrt0 o libraries L usr lib threads lpthreads 1c128 1c profl
547. ructure use the same base address you should group external data into structures or arrays wherever it makes sense to do so z preprocessor directive can improve the nie EAE of optimized code by allowing the amem to make less pessimistic assumptions about the storage of external and static variables Because the compiler treats register variables the same as it does automatic variables you do not gain anything by declaring register variables Note that this differs from other implementations where using the register attribute can greatly affect program performance Related Reading Pointers Keeping track of pointers during optimization is difficult and in some cases impossible Using pointers inhibits most memory optimization such as dead store elimination and store motion Using the 4 5 age 364 preprocessor directive to list identifiers that do not share the same physical storage can improve the runtime performance of optimized code Also see for information on applying aliasing assertions to pointers in your compilation unit 198 C for AIX User s Guide Related Reading Functions Declare nonmember functions as static whenever possible This will soeed up calls to the function Related Reading C f on Araumen KEyoressions Function Arguments Optimization is effective when function arguments are used It is usually better to pass a value as an argument to a function than to le
548. rved 3 3 4 Related Reading Implementation Dependency Registers F 3 8 Objects in registers declared with the storage class specifier register are treated as int objects 3 5 1 Related Reading 452 C for AIX Users Guide Implementation Dependency Structures Unions Enumerations Bit Fields A 6 3 9 F 3 9 lf a union object is accessed using a member of a different type the result is undefined 3 3 2 3 The alignment and padding of structures and unions are subject to the following rules 3 5 2 1 e Padding is added to align the structure and union members on their natural boundaries e Padding is added to the end of structures and unions on their natural boundary e The alignment of a structure or union is that of its strictest member An unsigned int bit field is equivalent to a plain int bit field 3 5 2 1 Bit fields within an int are allocated from low memory to high memory For example 0x12345678 is stored with byte 0 containing 0x12 and byte 3 containing 0x78 3 5 2 1 The type of an enum bit field is the underlying type of the enumeration The maximum bit field length for the compiler is 32 bits If a series of bit fields does not add up to the size of an int padding may take place Bit fields cannot cross a storage unit boundary For example in the following struct with bit fields mapped as shown struct S unsigned int bit 30 unsigned int bit 3 unsigned int bit 8 the 3 bi
549. ry 491 double precision The use of two computer words to represent a floating point value in accordance with the required precision E element The component of an array subrange enumeration or set else clause The part of an if statement that contains the word else followed by a statement The else clause provides an action that is executed when the if condition evaluates to zero false enumeration constant An identifier that has an associated integer value defined by an enumeration type You can use an enumeration constant anywhere an integer constant is allowed enumeration tag The identifier that names an enumeration data type enumeration type An enumeration type defines a set of enumeration constants enumerator An enumeration constant and its associated value escape sequence A representation of a nonprintable character in a character or string literal An escape sequence contains the symbol followed by one of the characters a b f n r t v or or followed by one to three octal digits or followed by an x followed by any number of hexadecimal digits exception Any user logic or system error detected by a function that does not itself deal with the error but passes the error on to a handling routine expression A representation of a value For example variables and constants appearing alone or in combination with operators are expressions external data definition A definition appearing o
550. ry myaccount does exist the executable file produced by the compiler is placed in the myaccount directory Related Reading once Option Type Default Value pragma options Syntax qonce qnoonce ONCE NOONCE 306 C for AIX User s Guide Purpose Avoids including a header file more than once even if it is specified in several of the files you are compiling Notes The compiler uses the full path name to determine if a file has already been included No attempt is made to resolve or in the path name include statements that include or in the path statements may cause the same file to be included more than once The pragma options keyword ONCE may appear anywhere in your code It can be turned on and off by specifying ONCE and NOONCE respectively Important Do not use the qonce option if both of the following conditions are true 1 You include both stdio h and stdarg h in that order in your source files and 2 You are using the macro va_list va_list must be defined twice to have any effect and qonce defeats this purpose Example The following example shows how the compiler resolves whether a file has already been included include lt stdio h gt Found in usr include stdio h include lt stdio h gt Already included x include lt usr include stdio h gt Already included include lt stdio h gt Resolves to usr include stdio h which is the same file but this
551. s lt gt lt and gt Pointer comparisons are defined only when the pointers point to elements of the same array Pointer comparisons using the and operators can be performed even when the pointers point to elements of different arrays You can assign to a pointer the address of a data object the value of another compatible pointer or the NULL pointer Passing Pointer Values to Functions Pointers allow a called function to alter the value of a variable in the calling function Any changes to a 92 C for AIX User s Guide variable passed as an argument to a called function are not returned to the calling function However if a pointer to a variable is passed as an argument the called function can alter the value of the variable the pointer refers to Related Reading KA TDL Address Examples of Pointer Declaration and Use The following program shows how you can pass a pointer to a function and change the value of the object the pointer points to RE KK EKER k k k EKER RARER k K k KERR k K k K RRR KEKE RRR ERR ERK RRR ERE ERK KK k Kk Kk RE xx This program accepts a value for a timer then decreases xx this timer value by one each time the function count down xx is called KA KKK KK KEK KERR ERK EK KEKE KKK KERR KERR ERK ER AER EERE KK ER ERE kk kk kkk kkk include lt stdio h gt int count_down int timer int main void int t_timer local storage printf Set timer to _ n sc
552. s To use _debug_strnset you must compile with the debug memory qheapdebug compiler option This option maps all strnset calls to debug_strnset You do not have to change your source code in order for debug memset to verify the heap Note The qheapdebug option maps all calls to memory management functions including a heap specific version to their debug counterparts To prevent a call from being mapped parenthesize the function name Appendix F C for AIX Debug Functions 425 Return Value _debug_sirnset returns a pointer to the altered string There is no error return value Example This example contains two programming errors The string str was created without a null terminator to mark the end of the string and without the terminator strnset with a count of 10 stores bytes past the end of the allocated object include lt stdlib h gt include lt stdio h gt include lt string h gt int main void char str str char malloc 10 printf This is the string after strnset s n str return 0 BRK KEK KEKE KKK RRR k KERR KERR RRR ER KER k K k K k K KERR RRR EKER ERE RK RRR Kk KK K Kk Kk KK k Kk Kk Kk k The output should be End of allocated object 0x00073c80 was overwritten at 0x00073c8a The first eight bytes of the memory block in hex are 7878787878797979 This memory block was re allocated at line number 9 in strnset c Heap state was valid at line 11 of strnset c K KK K k K A k K k K k KKK K k
553. s To prevent a call from being mapped parenthesize the function name To reallocate or free memory allocated by _debug_malloc use debug _realloc and debug free you can also use realloc and free if you do not want debug information about the operation A heap specific version of this function _debug_umalloc is also available debug malloc always allocates memory from the default heap Return Value _debug_malloc returns a pointer to the reserved space If not enough memory is available or if size is O _debug_malloc returns NULL Example This example allocates 100 bytes of storage It then attempts to write to storage that was not allocated When _debug_malloc is called again heap check detects the error generates several messages and stops the program Note You must compile this example with the qheapdebug option to map the malloc calls to _debug_malloc include lt stdlib h gt include lt stdio h gt int main void char ptrl ptr2 if NULL ptr1 char malloc 100 puts Could not allocate memory block exit EXIT_FAILURE ptrl 1 a overwrites storage that was not allocated ptr2 char malloc 10 this call to malloc invokes _heap check x puts debug malloc did not detect that a memory block was overwritten return 0 BRK KEK RRR KKK KER KERR ERK ERK ERR ERR KK ERK EKER RRR KEKE RRR RRR ERA ERERRKERKERK RK Possible output is 412 C for AIX User s Guide Header info
554. s but static int objects are All assignment operators evaluate their right operand and assign that value to the left operand The left operand must evaluate to a reference to an object The address operator amp requires an lvalue as an operand while the increment and the decrement operators require a modifiable lvalue as an operand Expression Lvalue of Expression x 42 x xptr newvalue xptr at a Related Reading Types of Expressions Primary Expressions A primary expression can be any of the following e identifier e string literal e parenthesized expression e constant expression e function call e array element specification e structure of union member specification All primary operators have the same precedence and have left to right associativity Unary Expressions A unary expression contains one operand and a unary operator All unary operators have the same precedence and have right to left associativity The usual arithmetic conversions are performed on the operands of most unary expressions Binary Expressions A binary expression contains two operands separated by one operator Not all binary operators have the same precedence All binary operators have left to right associativity The usual arithmetic conversions are performed on the operands of most binary expressions The order in which the operands of most binary operators are evaluated is not specified To ensure correct results avoid crea
555. s etc are still produced if their corresponding options are set Appendix A Compiler Options 327 Example To check the syntax of myprogram c without generating an object file enter xlc myprogram c qsyntaxonly Or xlc myprogram c o testing qsyntaxonly Note that in the second example the qsyntaxonly option overrides the Fo on page 304 option so no object file is produced Related Reading suppress Option Type Default Value pragma options aopton rosuppress Syntax qsuppress msg_num msg_num qnosuppress Purpose This compiler option lets you specify warning or information messages to be suppressed in compiler listings or screen displays Notes This option suppresses compiler messages only and has no effect on linker or operating system messages Compiler messages that cause compilation to stop such as S and U level messages or other messages depending on the setting of the qhalt compiler option cannot be suppressed For example if the qhalt w compiler option is set warning messages will not be suppressed by the qsuppress compiler option The qnosuppress compiler option cancels previous settings of qsuppress Example Assuming a sample program called myprogram c shown below pragma incorrect pragma void Compiling the program above would normally result in the following or similar compiler message t c line 1 1 1506 224 I Incorrect pragma ignored To suppres
556. s a data object safely Notes This option is obsolete Use qalias in your new applications This option has no effect unless you also specify the O option The default with xic and c89 is ansialias The optimizer assumes that pointers can only point to an object of the same type The default with cc is noansialias If you select noansialias the optimizer makes worst case aliasing assumptions It assumes that a pointer of a given type can point to an external object or any object whose address is already taken regardless of type The following are not subject to type based aliasing e Signed and unsigned types for example a pointer to a signed int can point to an unsigned int e Character pointer types can point to any type e Types qualified as volatile or const for example a pointer to a const int can point to an int Example To specify worst case aliasing assumptions when compiling myprogram c enter xlc myprogram c 0 qnoansialias 236 C for AIX User s Guide Related Reading arch Option Type Default Value pragma options fp aoptin e Syntax garch suboption Purpose Specifies the general processor architecture for which the code instructions should be generated Notes If you want maximum performance on a specific architecture and will not be using the program on other architectures use the appropriate processor architecture option You can specify the architecture using the following basic
557. s a preview aid to discover possible 32 to 64 bit migration problems Informational messages are displayed where data conversion may cause problems The 64 bit compiler mode such as possible e truncation due to explicit or implicit conversion of long types into int types e unexpected results due to explicit or implicit conversion of int types into long types e invalid memory references due to explicit conversion by cast operations of pointer types into into types e invalid memory references due to explicit conversion by cast operations of int types into pointer types e problems due to explicit or implicit conversion of constants into long types e problems due to explicit or implicit conversion by cast operations of constants into pointer types e conflicts with pragma options arch in source files and on the command line Related Reading ne na Comboler Onotion of 64 0 xcall Option Type Default Value pragma options P aopton e Syntax qxcall qnoxcall Purpose Generates code to static routines within a compilation unit as if they were external routines Notes qxcall generates slower code than qnoxcall Example To compile myprogram c so all static routines are compiled as external routines enter xlc myprogram c qxcal 338 C for AIX User s Guide Related Reading xref Option Type Default Value pragma options Syntax qxref qnoxref XREF NOXREF Purpose Produces a compiler listing tha
558. s are enabled using the qflttrap enable option or the Base Operating System BOS Runtime Service routine fp_enable The enable suboption inserts code into the prologue of the main program to enable the exceptions specified by the qflttrap option The suboption has no effect on source files that do not contain a main program The qflttrap imprecise suboption generates code that checks for the specified exceptions only on entry and exit to functions that perform floating point computations If an exception occurs it is detected but the exact location of the exception is not determined When the imprecise suboption is not specified each floating point operation in the code compiled with the qflttrap option is checked Unless the exception occurred during a call to another function that was not compiled with qflttrap for example a library routine the exact location of any exception is identified Specifying the qflttrap option with no suboptions is equivalent to setting qflttrap ov und zero inv inex The exceptions are not automatically enabled and all floating point operations are checked to provide precise exception location information By default the TRAP signals generated by enabled exceptions cause a program to stop Alternatively the exceptions can be acted upon by a program by providing a routine that is to be invoked when a TRAP signal occurs and by calling the BOS Runtime Service routine to specify that routine as the handler
559. s file scope static variables declared in other files Restrictions You cannot declare a static function at block scope Related Reading Examples Using static Storage Classes The following program shows the linkage of static identifiers at file scope This program uses two different external static identifiers named stat_var The first definition occurs in File 1 The second definition occurs in File 2 The main function references the object defined in File 1 The var_print function references the object defined in File 2 File 1 BRK EK RRR k k k KERR k k KR k RR ERR RK RE RRR RK ERR KK KK k Kk KEKE KERR RE KK k Kk Kk K xx Program to illustrate file scope static variables kx KKKA KKKA KKK KKKA KK KK KEK KK kK KKK KK KERR Kk KK KKK Kk Kk k kk kk kkk kk kk kkk kk include lt stdio h gt extern void var_print void Static stat_var 1 int main void Chapter 6 The C Language 113 printf filel stat_var d n stat_var var_print printf FILE1 stat_var d n stat_var return 0 File 2 BRK RRR RR KR ERR RK RRR k k kk ERR ER KEKE RRR RARER RE REE KK kK EER ER RRR RK KK KKK K xx This file contains the second definition of stat_var kk KA KK KKK KERR EK kkk kkk kk kkkkkkkkkkkkkkkkkk kkk KEKE ERR REE include lt stdio h gt static int Stat var 2 void var_print void printf file2 stat_var d n stat_var This program produces the following output filel stat_var 1 file2 stat_var 2 FILE sta
560. s in a function prototype It is visible from the point where it is declared to the closing parenthesis of the prototype declaration Related Reading Statement Program Linkage Between Identifiers The association or lack of association between two identical identifiers is known as linkage The kind of linkage that an identifier has depends on the way that it is declared 54 for AIX User s Guide Types of identifier linkage and their descriptions are Internal Linkage External Linkage No Linkage Related Reading Internal linkage occurs where identical identifiers within a single source file refer to the same data object or function The following kinds of labels have internal linkage e All identifiers with file or block scope that have the keyword static in their declarations Functions with static storage class are visible only in the source file in which you define them e C identifiers declared at file scope with the specifier const and not explicitly declared extern A variable that has static storage class can be defined within a block or outside of a function e If the defnition occurs within the block the variable has internal linkage and is visible only within the block after its declaration is seen e lf the definition occurs outside of a function the variable has internal linkage and is available from the point where it is defined until the end of the current source file A class name that
561. s in an expression are single precision The results of expressions are then rounded to single precision if they are assigned to float variables Other C compilers might evaluate floating point expressions in single precision where such an evaluation is permitted by the language definition This implementation is preferred on machines where single precision operations are faster than double precision operations In general floating point results from programs compiled using C for AIX and executed on the RISC System 6000 system are more accurate than those from other implementations because of the higher Chapter 4 Advanced Compiler Usage 27 precision used for intermediate results and the use of maf operations Related Reading qfloat nomaf The nomaf option is provided for cases where it is necessary to exactly duplicate the double results of an implementation that does not have multiply add operations The nomaf option prevents the compiler from generating any multiply add operations Not using multiply add operations decreases accuracy and performance but strictly conforms to the IEEE standard for double precision arithmetic To duplicate the single precision results from other implementations you may also need to use the qfloat rndsngl option qfloat hssngl The qfloat hssngl option improves the performance of single precision float floating point calculations by suppressing certain rounding operations The suppressed roun
562. s of string Savona Dr perm_address city address of string Dundas perm_address prov address of string Ontario perm_address postal_code address of string L4B 2A1 The following definition shows a partially initialized structure struct address int street_no char street_name char city char prov char postal code bs struct address temp address 44 Knyvet Ave Hamilton Ontario The values of temp_address are Member Value temp_address street_no 44 temp_address street_name address of string Knyvet Ave temp_address city address of string Hamilton temp_address prov address of string Ontario temp_address postal_ code value depends on the storage class Note The initial value of uninitialized structure members like temp_address postal_code depends on the Storage class associated with the member Alignment of Structures Structures are aligned according to the setting of the qalign compiler option which specifies the alignment rules the compiler uses when laying out memory storage for structures and unions The mapping of a structure is based on the alignment setting in effect at the beginning of the structure definition 96 C for AIX User s Guide Structures and unions with identical members but using different alignment are not type compatible and cannot be assigned to each other Use the qextchk compiler option to check for alignment mismatches and refer to the attribute section of the comp
563. s the value of the expression The left operand is evaluated possibly producing side effects and the value is discarded The result of a comma expression is not an lvalue Both operands of a comma expression can have any type All comma expressions have left to right associativity The left operand is fully evaluated before the right operand Constant Expressions A constant expression is an expression with a value that is determined during compilation That value can be evaluated at runtime but cannot be changed Constant expressions can be composed of integer character floating point and enumeration constants as well as other constant expressions Some constant expressions such as string literals or address constants are lvalues The C language requires constants in the following places e In the subscript declarator as the description of the array bound e After the keyword case in a switch statement e In an enumerator as the numeric value of an enum constant e Ina bit field width specifier e Inthe preprocessor if statement enumeration constants address constants and sizeof cannot be used in the preprocessor if statement e In the initializer of a file scope data definition Chapter 6 The C Language 71 In all of these contexts except for an initializer of a file scope data definition the constant expression can contain integer character and enumeration constants casts to integral types and sizeof expressions F
564. s this message compile the sample program with the qsuppress option as follows xlc myprogram c qsuppress 1506 224 328 C for AIX User s Guide Related Reading Option Type Default Value pragma options stag Sete Syntax tprograms Purpose Adds the prefix specified by the B option to the designated programs Notes This option can only be used with the B option The flags representing the standard program names are Programs Description Compiler front end b Compiler back end p Compiler preprocessor a Assembler I Interorocedural Analysis tool compile phase L Interprocedural Analysis tool link phase 1 Linkage editor 7 Linkage helper munch Default If B is specified but prefix is not the default prefix is lib o If Bprefix is not specified at all the prefix of the standard program names is lib n If B is specified but torograms is not the default is to construct path names for all the standard program names c b I a I and m Example To compile myprogram c so that the name u newones compilers is prefixed to the compiler and assembler program names enter xlc myprogram c B u newones compilers tca Related Reading tabsize Option Type Default Value pragma options fp aoptin tase Syntax Appendix A Compiler Options 329 qtabsize n Purpose Changes the length of tabs as perceived by the compiler Notes nis the number of character spaces representing a tab in
565. same including any supplied by configuration files e f you do compile a program with qpdf1 remember that it will generate profiling information when it runs which involves some performance overhead This overhead goes away when you recompile with qpdf2 or with no PDF at all The following commands are available for managing the PDFDIR directory resetpdf pathname Zeros out all profiling information but does not remove the data files from the pathname directory or if pathname is not specified from the PDFDIR directory or if PDFDIR is not set from the current directory When you make changes to the application and recompile some files the profiling information for those files is automatically reset because the changes may alter the program flow Run resetpdf to reset the profiling information for the entire application after making significant changes that may affect execution counts for parts of the program that were not recompiled cleanpdf pathname Removes all profiling information from the pathname directory or if pathname is not specified from the PDFDIR directory or if PDFDIR is not set from the current directory Removing the profiling information reduces the runtime overhead if you change the program and then go through the PDF process again Run this program after compiling with qpdf2 or after finishing with the PDF process for a particular application If you continue using PDF with an application after running
566. saved to the current directory qnogenpcomp Does not generate precompiled header files qgenpcomp and qusepcomp will be ignored if they are both specified along with the a or ae options Without the qusepcomp option qgenpcomp is accepted in all cases Example To compile myprogram c and generate a precompiled header file for any files that have changed since the last compilation or for any files that do not have precompiled header files and then place them in the directory headers enter xlc myprogram c qgenpcomp headers The new precompiled header is called csetc pch Related Reading genproto Option Type Default Value pragma options aopton ogenproto Syntax qgenproto qgenproto parmnames qnogenproto Purpose Produces ANSI prototypes from K amp R function definitions This should help to ease the transition from K amp R to ANSI Notes Using qgenproto without PARMnames will cause prototypes to be generated without parameter names Parameter names are included in the prototype when PARMnames is specified Example For the following function foo c foo a b c float a int b 268 C for AIX User s Guide specifying xlc c qgenproto foo c produces int foo double int int The parameter names are dropped On the other hand specifying xlc c qgenproto parm foo c produces int foo double a int b int c In this case the parameter names are kept Note that float a is represente
567. second there stored as there Q char xthird Hello there stored as Hello there 0 x A character string constant has type array of char and static storage duration A wide character constant has type array of wchar_t and static storage duration Chapter 6 The C Language 51 Use the escape sequence n to represent a new line character as part of the string Use the escape sequence to represent a backslash character as part of the string You can represent the single quotation mark symbol by itself but you use the escape sequence to represent the double quotation mark symbol For example include lt stdio h gt void main char s Hi there n char p The backslash character char q The double quotation mark n printf s s n s S p q This program produces the following output Hi there The backslash character The double quotation mark You should be careful when modifying string literals because the resulting behavior depends on whether your strings are stored in read write static memory Use the ro compiler option or the pragma strings preprocessor directive to change the default storage for string literals The pragma strings preprocessor directive can also be used to specify whether string literals are readonly or read write The following are examples of string literals char titles Handel s Water Music char mail_addr Last Name
568. sed to store the constant Data Types for Integer Constants Assigned Constant Value Data Type unsuffixed decimal int long int unsigned long int unsuffixed octal int unsigned int long int unsigned long int unsuffixed hexadecimal int unsigned int long int unsigned long int suffixed by u or U unsigned int unsigned long int suffixed by I or L long int unsigned long int suffixed by both u or U andlor L unsigned long int suffixed by Il or LL long long int unsigned long long int suffixed by both u or U and Il or LL unsigned long long int A plus or minus symbol can precede the constant It is treated as a unary operator rather than as part of the constant value Note that the integer constant 2147483648 is not valid because 2147483648 is an unsigned int value which cannot have the unary minus operator applied to it Instead this value should be coded as 2147483647 1 To avoid such problems with very small integral values you should use the identifiers INT_MIN for int SHRT_MIN for short int and SCHAR_MIN for signed char These and other limits for integer values are set in the usr include limits h include file Header files are described in the AIX Version 4 Files Reference Decimal Values A decimal constant contains any of the digits O through 9 The first digit cannot be 0 48 C for AIX Users Guide gigir Fo to GIGI foto Y gt lt gt gt Integer constants beginning with the digit O are i
569. sequence of statements accomplishes the same task Note the use of the while statement instead of the for statement count 1 while count lt 20 printf count d n count count The following for statement does not contain an initialization expression for index gt 10 index listLindex varl var2 printf list d d n index list index The following for statement will continue running until scanf receives the letter e 150 C for AIX User s Guide Tor 23 scanf c amp letter if letter n continue if letter e break printf You entered the letter c n letter The following for statement contains multiple initializations and increments The comma operator makes this construction possible for i 0 j 50 i lt 10 i j 50 printf i 2d and j 3d n i j The following example shows a nested for statement It prints the values of an array having the dimensions 5 3 for row 0 row lt 5 row for column 0 column lt 3 column printf d n table row column The outer statement is processed as long as the value of row Is less than 5 Each time the outer for statement is executed the inner for statement sets the initial value of column to zero and the statement of the inner for statement is executed 3 times The inner statement is executed as long as the value of column is less than 3 Related Reading A onilnue
570. ser s Guide Related Reading struct Structures A structure contains an ordered group of data objects Unlike the elements of an array the data objects within a structure can have varied types Each data object within a structure is called a member or field Use structures to group logically related objects For example to allocate storage for the components of one address define the following variables int street_no char street_name char city char prov char postal code Declaring a Structure Pi struct eee lt 4 L he entifier_ identifier Provides a tag name for the structure If specified subsequent declarations in the same scope of variables using the structure can be made by referring to the tag name If not specified you must place all variable definitions that refer to the structure within the declaration of the data type member The list of members provides the data type with a description of the values that can be stored in the structure be tyne_speciie decker consent ENDES SON deckreter A member that does not represent a bit field can be of any data type and can have the volatile or const qualifier If a colon and a constant expression follow the member declarator the member represents a bit field Bit fields are described in Declaring and Using Bit Fields in Structures page 7 A structure type declaration describes the members that are part of the structure Iden
571. setting This option greatly restricts the amount of interprocedural optimization for calls to unknown functions Specifies that the missing functions are not known to be safe isolated or pure partition size Specifies the size of each program partition created by IPA during pass 2 Size can be any of e small e medium e large e any positive integer value The size of the partition is directly proportional to the time required to link and the quality of the generated code When partition sizes are large the time to complete linkage is longer but the quality of the generated code is generally better An integer may be used to specify partition size for finer control This integer is in terms of unspecified units and its meaning may change from release to release Its use should be limited to very short term tuning efforts pure name name Specifies a list of pure functions that are not compiled with qipa Any function specified as pure must be isolated and safe and must not alter the internal state nor have side effects defined as potentially altering any data visible to the caller safe name name Specifies a list of safe functions that are not compiled with qipa Safe functions can modify global variables but may not call functions compiled with qipa unknown name name Specifies a list of unknown functions that are not compiled with qipa Any function specified as unknown can make calls to other parts of the program compil
572. sing the undef preprocessor directive The Uname option has a higher precedence than the Dname option Example To compile myprogram c so that the definition of the name COUNT is nullified enter xlc myprogram c UCOUNT For example if the option DCOUNT 1000 is used a source line undefine COUNT is generated at the top of the source Related Reading unroll Option Type Default Value pragma options Psaooion moe Syntax qunroll n qnounrol Purpose Unrolls inner loops in the program by a factor of n Notes When qunroll is specified the bodies of inner loops will be duplicated n 1 times creating a loop with n Original bodies The loop control may be modified in some cases to avoid unnecessary branching The maximum value for nis 8 Default The compiler will perform automatic unrolling of inner loops by a factor of 4 at an optimization level of 2 or higher for example when the O3 optimizing option is specified This will be disabled however if qnounroll is specified at the same time Example In the following example loop control is not modified while s Q xpt S Unrolling this by a factor of 2 gives Appendix A Compiler Options 333 while gt s xpt S if s 0 break ADT ASTI In this example loop control is modified for i 0 i lt n i ali b i cli Unrolling by 3 gives 1 0 if i gt n 2 goto remainder for i lt n 2 i 3
573. sion of an integral type to long long int only occurs if one of the operands in the expression being evaluated has type long long int e When a value of float type is converted to long long type the fractional part is discarded If the value of the integral part cannot be represented by the long long int type the result is the maximum value of the long long int type e When a value of long long int type is converted to floating type if the value being converted is in the range of values that can be represented but cannot be represented exactly the result is either the nearest higher or nearest lower value depending on the IEEE rounding mode You set the compile time IEEE rounding mode with the y compiler option e For binary operators that expect operands of arithmetic type if either operand has type unsigned long long int the other operand is converted to unsigned long long int Otherwise if either operand has type long long int the other operand is converted to long long int e The maximum size of a bit field remains 32 bit e A conversion specification may contain an optional Il specifying that a following d i O u x or X conversion specifier applies to a long long int or unsigned long long int argument e For power alignment rules long long int identifiers and aggregates containing long long int members are aligned on a 64 bit boundary e For type based aliasing lvalues of type char unsigned char long long int or unsigned long l
574. sion that contains more than one multiplication operator For example the expression sites number cost can be interpreted in any of the following ways sites number cost sites number cost cost sites number Division The division operator yields the quotient of its operands The operands must have an arithmetic type The result is not an Ivalue If both operands are positive integers and the operation produces a remainder the remainder is ignored For example expression 7 4 yields the value 1 rather than 1 75 or 2 On all IBM C compilers if either operand is negative the result is rounded towards zero The result is undefined if the second operand evaluates to 0 For more information on generating warning messages for division by constant zero see the qinfo compiler option The usual arithmetic conversions on the operands are performed 124 C for AIX User s Guide Remainder The remainder operator yields the remainder from the division of the left operand by the right operand For example the expression 5 3 yields 2 The result is not an lvalue Both operands must have an integral type If the right operand evaluates to 0 the result is undefined If either operand has a negative value the result is such that the following expression always yields the value of a if b is not 0 and a b is representable a b bta The sign of the remainder is the same as the sign of the quotient
575. slation is the process of transforming all or part of a Source program into a program image that contains all the information needed for the program to run Each nonempty sequence of white space characters in a source program other than the new line character is replaced by one space character Comments are treated as white space 2 1 1 2 If you use the C compiler option comments are retained Diagnostic messages have the following format 2 1 1 3 15cc nnn severity text where cC Is a two digit code indicating the compiler component that issued the message 00 Code generation or optimization message 01 Compiler services message 05 Front end text message 06 Front end error message nnn Is the message number severity Is a letter representing the severity level of the message text Is the message text describing the error Diagnostic messages have the following severity levels Informational Compilation continues The message reports conditions found during compilation Warning Compilation continues The message reports valid but possibly unintended conditions Compilation continues and object code is generated Error conditions exist that the compiler can correct but the program might not run correctly 446 C for AIX Users Guide Severe error Compilation continues but object code is not generated Error conditions exist that the compiler cannot correct Unrecoverable error The compiler halts An internal com
576. sociated with fd not associated with a stream _ stream Note Messages 89 to 92 and 94 to 108 are reserved for future use Memory calloc malloc and realloc Functions If the size requested is zero the calloc malloc and realloc functions return a null pointer 4 10 3 abort Function When the abort function is called open and temporary files are closed and temporary files are erased 4 10 4 1 exit Function If the value of the argument to the exit function is other than zero EXIT SUCCESS or EXIT_FAILURE the process ends and returns the value as the return code 4 10 4 3 getenv Function Environment names are defined by the underlying shell being used 4 10 4 4 The environment list obtained by a call to the getenv function is altered in the following manner 4 10 4 4 1 The getenv function searches the environment list for a string of the form name value 2 The getenv function returns a pointer to the value in the current environment if such a string is present If such a string is not present a NULL pointer is returned 3 Acall to putenv is used The prototype for putenv is int putenv char 458 cC for AIX User s Guide 4 The string format is name value where name is the environment variable and value is the new value for it system Function The underlying command shell determines the format of the string that is passed to the system 4 10 4 5 The string that is passed to the system function goes d
577. ss information in the listing file The short suboption which is the default generates the Object File Map Source File Map and Global Symbols Map sections of the listing The long suboption causes the generation of all of the sections generated through the short suboption as well as the Object Resolution Warnings Object Reference Map Inliner Report and Partition Map sections Appendix A Compiler Options 281 lowfreq name name Specifies names of functions which are likely to be called infrequently These will typically be error handling trace or initialization functions The compiler may be able to make other parts of the program run faster by doing less optimization for calls to these functions missing attribute Specifies the interprocedural behavior of procedures that are not compiled with qipa and are not explicitly named in an unknown safe isolated or pure suboption The following attributes may be used to refine this information safe Functions which do not indirectly call a visible not missing function either through a direct call or through a function pointer isolated Functions which do not directly reference global variables accessible to visible functions Functions bound from shared libraries are assumed to be isolated pure Functions which are safe and isolated and which do not indirectly alter storage accessible to visible functions pure functions also have no observable internal state unknown The default
578. ssor Directive eee ew eneeaeao ee ao amp 4 00 pragma ibm independent_loop Preprocessor Directive 384 pragma ibm iterations Preprocessor Directive 2 2 2 384 pragma ibm parallel loop Preprocessor Directive 385 pragma ibm permutation Preprocessor Directive 2 2 4 385 pragma ibm schedule Preprocessor Directive 2 386 pragma ibm sequential_loop Preprocessor Directive 387 pragma omp parallel Preprocessor Directive 2 2 2 2 388 pragma omp for Preprocessor Directive 2 2 ee ee ee ee 889 pragma omp parallel for Preprocessor Directive 2 2 2 ww 393 pragma omp sections Preprocessor Directive a a ee ee ee ee 8983 pragma omp parallel sections Preprocessor Directive 394 pragma omp single Preprocessor Directive 2 ee ee ee ee 395 pragma omp master Preprocessor Directive 2 ew ee eee ee 395 Contents XI pragma omp critical Preprocessor Directive pragma omp barrier Preprocessor Directive pragma omp atomic Preprocessor Directive pragma omp flush Preprocessor Directive pragma omp ordered Preprocessor Directive pragma omp threadprivate Preprocessor Directive Built in Functions Used for Parallel Processing Run time Options for Paralle
579. ssor tokens 58 C for AIX User s Guide The preprocessed source program file must be a valid C program Preprocessor directives begin with the token followed by a preprocessor keyword The token must appear as the first character that is not white space on a line The is not part of the directive name and can be separated from the name with white spaces A preprocessor directive ends at the new line character unless the last character of the line is the backslash character If the character appears as the last character in the preprocessor line the preprocessor interprets the and the new line character as a continuation marker The preprocessor deletes the and the following new line character and splices the physical source lines into continuous logical lines Except for some pragma directives preprocessor directives can appear anywhere in a program Related Reading Preprocessing Operations Preprocessing carries out the following operations on your program source files 1 New line characters are introduced as needed to replace system dependent end of line characters and other system dependent character set translations are performed as needed Trigraph sequences are replaced by equivalent single characters 2 Each backslash followed by a new line character is deleted and the next source line is appended to the line that contained the backslash 3 The source text is decomposed into preprocessing tokens
580. stack segment Related Reading Interlanguage Calls Stack Overflow The RISC System 6000 linkage convention requires no explicit inline check for overflow The operating system uses a storage protect mechanism to detect stores past the end of the stack segment Related Reading Chapter 8 Using C for AIX with Other Programming Languages 213 Interlanguage Calls Traceback Table The compiler supports the traceback mechanism which is required by the AIX Version 4 Operating System symbolic debugger to unravel the call or return stack Each function has a traceback table in the text segment at the end of its code This table contains information about the function including the type of function as well as stack frame and register information Related Reading Interlanguage Calls Type Encoding and Checking Detecting errors before a program is run is a key objective of the C for AIX compiler Runtime errors are hard to find and a many are caused by mismatching subroutine interfaces or conflicting data definitions The C for AIX compiler uses a scheme for early detection that encodes information about all external symbols data and programs If the e e 258 option has been specified this information about external symbols is checked at bind or Flea time for consistency The Assembler Language Reference for the AIX RISC System 6000 book describes the following details of the Subroutine Linkage Convention e Register usa
581. suboptions auto Automatically detects the specific architecture of the compiling machine Use this suboption only if the execution environment is the same as the compilation environment com Produces object code that contains instructions that will run on all the POWER POWER2 and PowerPC hardware platforms that is the instructions generated are common to all platforms Using qarch com is referred to as compiling in common mode Defines the ARCH_ COM macro Use this option if you want your program to be portable pwr Produces object code that contains instructions that will run on any of the POWER and POWER2 hardware platforms Defines the ARCH _PWR macro pwr2 Produces object code that contains instructions that will run on the POWER2 hardware platforms Defines the ARCH PWR and ARCH PWR2 macros pwrx Produces object code that contains instructions that will run on the POWER2 hardware platforms same as qarch pwr2 Defines the ARCH PWR and ARCH _PWR2 macros ppc Produces object code that contains instructions that will run on any of the 32 bit PowerPC hardware platforms This suboption will cause the compiler to produce single precision instructions to be used with single precision data Defines the ARCH PPC macro ppcgr Produces object code that contains optional graphics instructions for PowerPC processors Defines the _ARCH_ PPC and ARCH PPCGR macros noauto Valid only when the O4 compiler option is in effect this option d
582. sult of the operation has always type int and is not an lvalue The following two expressions are equivalent lright right 0 The usual arithmetic conversions on the operand are performed Bitwise Negation The bitwise negation operator yields the bitwise complement of the operand In the binary representation of the result every bit has the opposite value of the same bit in the binary representation of the operand The operand must have an integral type The result has the same type as the operand but is not an lvalue Suppose x represents the decimal value 5 The 32 bit binary representation of x is 00000000000000000000000000000101 The expression x yields the following result represented here as a 32 bit binary number 11111111111111111111111111111010 The 32 bit binary representation of 0 is 11111111111111111111111111111111 Chapter 6 The C Language 121 Address The amp address operator yields a pointer to its operand The operand must be an Ivalue or function designator It cannot be a bit field nor can it have the storage class register If the operand is an Ivalue or function the resulting type is a pointer to the expression type For example if the expression has type int the result is a pointer to an object having type int The result is not an lvalue If p_to_y is defined as a pointer to an int and y as an int the following expression assigns the address of the variable y to the pointer p_to_y p_to_y ay
583. t x x Chapter 7 Writing C Programs 193 include lt string h gt Static HANDLE hFile Handle to memory file static void hMap Handle to allocated memory typedef struct mem_info void pBase Heap _t pHeap MEM_INFO T inithp Subprocess Version Function to create and open the heap with a named shared memory object je a static Heap t inithp void MEM_INFO_T info Info structure Open the shared memory file by name The file is based on the system paging swapper file hFile OpenFileMapping FILE MAP WRITE FALSE MYNAME_SHAREMEM if hFile NULL return NULL Figure out where to map this file by looking at the address in the shared memory where the memory was mapped in the parent process hMap MapViewOfFile hFile FILE MAP WRITE 0 0 sizeof info if hMap NULL return NULL Extract the heap and base memory address from shared memory memcpy info hMap sizeof info UnmapViewOfFile hMap hMap MapViewOfFileEx hFile FILE MAP WRITE 0 0 0 info pBase if _uopen info pHeap Open heap and check result return NULL return info pHeap termhp Function to close my view of the heap static int termhp Heap t uheap if _uclose uheap close heap return 1 UnmapVi ewOfFile hMap retu
584. t student amp section 0 You can assign the address of the first character in a string constant to a pointer by specifying the string constant in the initializer The following example defines the pointer variable string and the string constant abcd The pointer string is initialized to point to the character a in the string abcd char string abcd The following example defines weekdays as an array of pointers to string constants Each element points to a different string The pointer weekdays 2 for example points to the string Tuesday static char weekdays Sunday Monday Tuesday Wednesday Thursday Friday Saturday A pointer can also be initialized to NULL using any integer constant expression that evaluates to 0 for example char a 0 Such a pointer is a NULL pointer It does not point to any object Using Pointers Two operators are commonly used in working with pointers the address amp operator and the indirection operator You can use the amp operator to refer to the address of an object For example the following statement assigns the address of x to the variable p_ to x The variable p to x has been defined as a pointer int x p_to x p_to x amp X The indirection operator lets you access the value of the object a pointer refers to The following statement assigns to y the value of the object that p_to x points to Chapter 6 The C Language 91 float y p t
585. t optimization options specified on the command line apply to the entire C source program This option lets you override those default settings for specified functions func_name in your program Per function optimizations have effect only if optimization is already enabled by compilation option You can request per function optimizations at a level less than or great than that applied to the rest of the program being compiled Selecting options through this pragma affects only the specific optimization option selected and does not affect the implied settings of related options 374 C for AIX User s Guide Allowable settings for option are opt level 2 Same as specifying O2 for the specified function opt level 3 Same as specifying O3 for the specified function opt strict Same as specifying qstrict for the specified function opt strict yes Same as specifying qstrict for the specified function opt strict no Same as specifying qnostrict for the specified function opt compact Same as specifying qcompact for the specified function opt compact yes Same as specifying qcompact for the specified function opt compact no Same as specifying qnocompact for the specified function Selections for option are not subject to macro expansion This pragma affects only functions defined in your compilation unit and can appear anywhere in the compilation unit for example e before or after a compilation unit e before
586. t are deleted The default is to preprocess compile and link edit source files to produce an executable file Example To compile myprogram c and send the preprocessed source to standard output enter xlc myprogram c E If myprogram c has a code fragment such as define SUM x y x y int a define mm 1 This is a comment in a preprocessor directive iwm b This is another comment across two lines int e Another comment c SUM a Comment in a macro function argument b the output will be 254 C for AIX User s Guide line 2 myprogram c int a line 5 int pi int C C a b Related Reading enum Option Type Default Value pragma options Syntax qenum small qenum int qenum intlong qenum 1 qenum 2 qenum 4 qenum 8 ENUM SMALL ENUM INT ENUM INTLONG ENUM 1 ENUM 2 ENUM 4 ENUM 8 ENUM RESET Purpose Specifies the amount of storage occupied by enumerations Notes Valid suboptions are qenum smal Specifies that enumerations occupy a minimum amount of storage either 1 2 or 4 bytes of storage depending on the range of the enum constants qenum int Specifies that enumerations occupy 4 bytes of storage and are represented by int qgenum intlong Specifies that enumerations occupy 8 bytes of storage and are represented by long if q64 is specified and the range of the enum constants exceed the limit for int genum 1 Specifies
587. t as the power suboption except that it also applies alignment rules to doubles and long doubles that are not the first member of a structure or union If you use the galign option more than once on the command line the last alignment rule specified applies to the file Within your source file you can use pragma options align reset to revert to a previous alignment rule The compiler stacks alignment directives so you can go back to using the previous alignment directive without knowing what it is by specifying the pragma align reset directive For example you can use this option if you have a class declaration within an include file and you do not want the alignment rule specified for the class to apply to the file in which the class is included You can code pragma options align reset in a source file to change the alignment option to what it was before the last alignment option was specified If no previous alignment rule appears in the file the alignment rule specified in the invocation command is used Example 1 Imbedded pragmas Using the compiler invocation xlc qalign mac68k file c lt default alignment rule for file is Macintosh 234 C for AIX User s Guide Where file c has struct A int a struct B char cC double d pragma options align power lt B will be unaffected by this pragma unlike previous behavior Macintosh alignment rules still x in effect BB pra
588. t bit field following the 30 bit bit field would cross a 32 bit word storage boundary Because crossing a word boundary is not allowed the 30 bit field is padded and the 3 bit field starts another word The qalign option allows you to specify different bit field alignment rules Values of an enumeration type are represented by the integral type signed int 3 5 2 2 You can use the qenum small compiler option to minimize the size of enumerations to 1 2 or 4 bytes Related Reading Implementation Dependency Qualifiers F 3 10 For access to an object that has a type qualified as volatile all access is retained 3 5 5 3 The volatile attribute maintains consistency in memory access to data objects Volatile objects are read from memory each time their value is needed and written back to memory each time they are changed When optimizing the code the compiler cannot remove any access to a volatile variable The volatile attribute is useful for objects such as the system clock that have values that may be changed in ways unknown to your program For example in the following program fragment Appendix Implementation Dependencies Overview 453 atile int i all of these statements are kept by the compiler even if the O option to optimize the code is active If int was not defined as volatile only i 6 would be kept in the optimized code Related Reading Implementation Dependency Declarators F 3 11 There is no l
589. t can point to an unsigned int e Character pointer types can point to any type e Types qualified as volatile or const For example a pointer to a const int can point to an int Example To specify worst case aliasing assumptions when compiling myprogram c enter Appendix A Compiler Options 233 xlc myprogram c 0 qgalias noansi Related Reading align Option Type Default Value pragma options align full ALIGN suboption Syntax galign suboption ALIGN suboption Purpose Specifies what aggregate alignment rules the compiler uses for file compilation Use this option to specify the maximum alignment to be used when mapping a class type object either for the whole source program or for specific parts Notes The qalign suboptions are power The compiler uses the RISC System 6000 alignment rules full The compiler uses the RISC System 6000 alignment rules The power suboption is the same as full mac68k The compiler uses the Macintosh alignment rules twobyte The compiler uses the Macintosh alignment rules The mac68k suboption is the same as twobyte packed The compiler uses the packed alignment rules bit_packed The compiler uses the bit_packed alignment rules Alignment rules for bit_packed are the same as that for packed alignment except that bitfield data is packed on a bit wise basis without respect to byte boundaries natural The compiler maps structure members to their natural boundaries This has the same effec
590. t for 64 bit support q64 compiler option If you want to generate code that will run across a variety of processors use the following guidelines to select the appropriate qarch and or qtune compiler options Code compiled with e qarch com will run on any RS 6000 e garch pwr will run on any POWER or POWER2 machine e qarch pwr2 or pwr2s pwrx p2sc will run only on POWER2 machines 16 C for AIX User s Guide e qarch ppc will run only on all PowerPC machines e q64 will run only on PowerPC machines with 64 bit support e other qarch options that refer to specific processors will run on any functionally equivalent PowerPC machine In the examples found in the table below code compiled with qarch pwr3 will also run on a rs64b but not on a rs64a Similarly code compiled with qarch 603 will run on a pwr3 but not on a rs64a Processor graphics support sqrt support 64 bit support 603 yes no no 604 yes no no rs64a no no yes rs64b yes yes yes pwr3 yes yes yes If you want to generate code optimized specifically for a particular processor acceptable combinations of q32 q64 qarch and qtune compiler options are shown in the table below If you specify incompatible combinations of these options the compiler will assume its own option selections as described in ae S R i 3 C Q omoliler Option Or A UIC ciol lS OF 04 0 OMpHaton on Dade I4 Predefined Macro Available Default qtune qtune options suboption _
591. t hsflt In suppressing rounding operations the hsflt option operates in the same way as the hssngl option However the hsflt option also suppresses rounding operations when double precision values are assigned to single precision variables Single precision overflow or underflow is not detected in such assignments and the assigned value is not properly rounded according to the current rounding mode For floating point to integer conversions the hsflt option allows the compiler to use inline code sequences instead of subroutine calls The inline code sequences do not check the floating point value and produce incorrect results in cases where the floating point value does not fall within the range of an integer Chapter 4 Advanced Compiler Usage 29 Use the qfloat hsflt option with the O option but not with the qfloat rndsngl or qfloat hssngl options qfloat rndsngl The qfloat rndsngl option is provided for cases where it is necessary to exactly duplicate the results of an implementation that uses single precision floating point arithmetic for float expressions The rndsngl option causes the compiler to round the results of floating point operations on float operands to single precision The effect of rounding the intermediate results to single precision is the same as if single precision operations had been used for evaluating float expressions Runtime performance can decrease significantly because of the increased rounding overh
592. t in function This pragma must be included in the source before the first function definition Once specified it applies to the rest of the file and cannot be turned off If a program source contains functions that you want compiled without pragma alloca place these functions in a different file Whenever you make a call to alloca you must include the header file lt malloc h gt to define alloca Header files are described in the AIX Version 4 Files Reference Related Reading pragma chars Preprocessor Directive The pragma chars directive specifies that the compiler is to treat all char objects as signed or unsigned pP pragma chars T oo i unsigned This pragma must appear before any statements in a file Once specified it applies to the rest of the file and cannot be turned off If a program file contains functions that you want compiled without pragma chars place these functions in a different file The chars compiler option has the same effect as this pragma The _CHAR_SIGNED or CHAR_UNSIGNED macros are defined according to the setting of the qchars option or corresponding preprocessor directives Appendix D Preprocessor Directives and Related Information 365 Related Reading pragma comment Preprocessor Directive The pragma comment directive places a comment into the object file PF praga comment compiler i User foken_stnng compiler The compiler appends the name
593. t includes a cross reference listing of all identifiers Notes Usage modes for xref are qxref full Reports all identifiers in the program qxref Reports only those identifiers that are used The qnoprint option overrides this option Any function defined with the pragma mc_func function_name directive is listed as being defined on the line of the pragma directive Example To compile myprogram c and produce a cross reference listing of all identifiers whether they are used or not enter xlc myprogram c qxref ful A typical cross reference listing has the form Identifier name Description of the item DM T M SR EY auto int in function adder O S9 O 36 1224 O0 45 122 IL Function invocation Column number Line number File Function definition Related Reading Option Type Default Value pragma options Syntax Appendix A Compiler Options 339 yrounding mode Yrounding_mode Purpose Specifies the compile time rounding mode of constant floating point expressions Notes rounding _mode must be one of the following n Round to the nearest representable number This is the default m Round toward minus infinity p Round toward plus infinity Z Round toward zero Example To compile myprogram c so that constant floating point expressions are rounded toward zero at compile time enter xlc myprogram c yz Related Reading 340 C for AIX User s Guide Appendix B 32 bit to 64 bit Mig
594. t is bin as asopt List of options for the assembler and not for the compiler These override all normal processing by the compiler and are directed to the assembler specified in the as stanza The string is formatted for the AIX getopt subroutine as a concatenation of flag letters with a letter followed by a colon if the corresponding flag takes a parameter cppcode Path name to be used for the code generation phase of the compiler The default is usr vac exe xlCcode ccomp C Front end The default is usr vac exe xIcentry codeopt List of options for the code generation phase of the compiler cppopt List of options for the lexical analysis phase of the compiler crt Path name of the object file passed as the first parameter to the linkage editor If you do not specify either the p or the pg option the crt value is used The default is lib crt0 o csuffix Suffix for source programs The default is c lowercase c dis Path name of the disassembler The default is usr vac exe dis Chapter 3 Using the C for AIX Compiler 13 gert inline inlineopt Id Idopt libraries2 mert options osuffix proflibs ssuffix use xlc Related Reading Path name of the object file passed as the first parameter to the linkage editor If you specify the pg option the gcrt value is used The default is lib grt0 o Path name to be used for the inlining phase of the compiler The default is usr vac exe xlCinline List of options
595. t of the definition and the initial value must be described by a constant expression OR e Reduce to the address of a previously declared object with static storage duration This object may be modified by adding or subtracting an integral constant expression If you do not explicitly initialize an extern variable its initial value is zero of the appropriate type Initialization of an extern object is completed by the time the program starts running Storage Storage is allocated at compile time for extern variables that are initialized Uninitialized variables are mapped at compile time and initialized to 0 zero at load time This storage is freed when the program finishes running Related Reading Examples Using extern Storage Classes The following program shows the linkage of extern objects and functions The extern object total is declared on line 12 of File 1 and on line 11 of File 2 The definition of the external object total appears in File 3 The extern function tally is defined in File 2 The function tally can be in the same file as main or in a different file Because main precedes these definitions and main uses both total and tally main declares tally on line 11 and total on line 12 File 1 Chapter 6 The C Language 109 1 Ekk kk kkk kk kkk kk kk kkk kk kkk kkk kkk kkk kkk kkk kk kk ERR ER kk RK EKER REE 2 xx The program receives the price of an item adds the 3 xx tax and prints the total cost of the item kk
596. t the function take the value from a global variable The E prag s page preprocessor directive lists functions that have no iE Heels ising the pragma to list functions that do not have side effects that is that do not modify global storage can improve the runtime performance of optimized code Related Reading Expressions If components of an expression are duplicate expressions code them either at the left end of the expression or within parentheses For example b x y z Duplicates recognized X Y Z d3 f x y a C e Chapter 7 Writing C Programs 199 x ty th x y Z No duplicates recognized x y z d f x ty xty th oOodna mwa II When components of an expression in a loop are constant code the expressions either at the left end of the expression or within parentheses If c d and e are constant and v w and x are variable the following examples show the difference in evaluation v w x c d e Loop invariant expressions recognized Ct d 6 gt Vor W x v w xx cxd e Optimization required for loop invariant vtwtxtctdte expressions to be recognized For integer expressions the loop invariant expression will be recognized if O is specified For floating point expressions the loop invariant expression will be recognized if O3 is specified Related Reading Critical Loops If your program contains a short heavily referenced for loop consid
597. t_var 1 The following program shows the linkage of static identifiers with block scope The test function defines the static variable stat_var which retains its storage throughout the program even though test is the only function that can refer to stat_var KEK kkk kk kk ERR kk kkk kk kk kkk kkk kkk KER AER KERR RRR ERE KER EKER ERE xx Program to illustrate block scope static variables kx KA KKK KK KKK KEK KEK KEK KEK KER KEK KER KR KK ERR ER KERR Kk kk kkk kkk kkk kkk kkk include lt stdio h gt int main void void test void int counter for counter 1 counter lt 4 counter test return 0 void test void static int stat_var auto int auto var 0 stat_var t auto vartt printf stat_var d auto var d n stat_var auto var 0 This program produces the following output stat_var 1 auto_var 1 stat_var 2 auto_var 1 stat_var 3 auto_var 1 stat_var 4 auto_var 1 Related Reading 114 C for AIX User s Guide typedef ee typedef tyee specter identivier teal A typedef declaration lets you define your own identifiers that can be used in place of type specifiers such as int float and double The names you define using typedef are not new data types They are synonyms for the data types or combinations of data types they represent A typedef declaration does not reserve storage When an object is defined using a typedef identifier the properties of the def
598. te array of an incomplete type an incomplete array of an incomplete array of int Example 3 Tags introduced at parameter scope are not exported to the enclosing non parameter scope int f struct a struct a int a int f struct ax i return i gt a The type struct a was introduced in a parameter list and will go out of scope at the end of the function declaration or definition 2 The C for AIX compiler may differ from XL C in implementation defined parts of the language e Apparent order of evaluation of arguments to functions with assignments will generate different results with XL C 1 3 and with C for AIX Other industry compilers may generate results with even greater differences This code is not portable and should be avoided include lt stdio h gt void func int i int j int k printf i d j d k d n i j k main int r 1 int c 0 func c r r r 4 With XL C 1 3 the results are isljsik 4 With C for AIX the results are i lj 4k 4 e Preprocessor differences include Copyright IBM Corp 1995 1999 467 Output preserves coordinates of each token No redundant line directives or multiple blank lines in output Erroneous incomplete macro invocations are expanded anyway This includes Extra arguments ignored Empty arguments Missing arguments treated as empty Incomplete argument list treated as completed 3 C for AIX differs from XL C where provisio
599. tem paging space To check the current paging space settings enter the command Isps a or use the AIX System Management Interface Tool SMIT command smit pgsp The paging space overview in AIX Version 4 System User s Guide Operating System and Devicesdescribes paging space and how to allocate it 488 cC for AIX User s Guide Appendix O Glossary This is a glossary of commonly used terms in the C for AIX information library It includes definitions developed by the American National Standards Institute ANSI and entries from the BM Dictionary of Computing ZC20 1699 It supplements the AIX Version 4 Topic Index and Glossary A address A name label or number identifying a location in storage a device in a system or network or any other data source arithmetic object An integral object or objects having the type float double or long double array element A single data item in an array assembler language A symbolic programming language in which the set of instructions includes the instructions of the machine and whose data structures correspond directly to the storage and registers of the machine assignment conversion A change to the form of the right operand that makes the right operand have the same data type as the left operand assignment expression An operation that stores the value of the right operand in the storage location specified by the left operand B binary expression An operation containing
600. ter 4 Advanced Compiler Usage Program Optimization with the C for AIX Compiler During optimization the compiler changes the unoptimized code sequences derived from the source code into equivalent optimized code sequences The resulting code runs faster and usually takes less space However during optimization compilation usually takes more time and space Because optimization transforms the code the direct correspondence between source and object code is often lost Therefore debugging information is not provided for programs compiled using the optimization option Optimized code is also more sensitive to subtle coding errors For these reasons do not use the optimization options while you are developing your programs Use the O optimization options only to compile the final versions of your programs Optimization Levels in C The default is not to optimize your program To optimize your program specify one of the following optimizing compiler options e O e 02 e 03 e 04 e qOPTimize e qOPTimize 2 e qOPTimize 3 e qOPTimize 4 When you specify optimization the compiler performs a complete control and data flow analysis for each function The compiler also uses global register allocation for the whole function thereby allowing many variables to be kept in registers rather than in memory The compiler performs optimizations such as Optimization Techniques Used by the C for AIX Compiler Technique Description of
601. the qlanglvl compiler option Related Reading pragma leaves Preprocessor Directive The pragma leaves directive takes a function name and specifies that the function never returns to the instruction following that function call Pe pogma leaves function TT 1 4 ANTHON Appendix D Preprocessor Directives and Related Information 373 If the specified function is not found a warning message is produced Related Reading pragma map Preprocessor Directive The pragma map directive tells the compiler that all references to an function identifier are to be converted to name Pre pragma map identifier amne d The following describes the options available for pragma map identifier Name of a function name External name that is to be bound to the given function The directive can appear anywhere in the program The identifier appearing in the directive is resolved as though the directive had appeared at file scope independent of its actual point of occurrence For example int func int void func void pragma map func funcnamel maps func to funcnamel Related Reading pragma option_override Preprocessor Directive The pragma option_override directives lets you specify alternate optimization options for specific functions ee pragma option_override func name option te lt l By defaul
602. the AIX Version 4 Operating System If the AIX system has never been installed on the system before the default locale is C The locale for United States English is en_US The default message catalogs in usr vac exe default_msg are called when e The C for AIX compiler cannot find message catalogs for the locale specified by L e The locale has never been changed from the default C For more information about the NLSPATH and LANG environment variables see the AlX Version 4 System User s Guide Operating Systems and Devices The AIX national language facilities are described in the Introducing National Language Support for Programming in the AIX Version 4 General Programming Concepts Related Reading Correcting Page Space Errors During Compilation If the AIX operating system runs low on paging space during a compilation the compiler issues one of the following messages 1501 229 Compilation ended due to lack of space 1501 224 fatal error in exe xlCcode signal 9 received lf lack of paging space causes other compiler programs to fail the following message is displayed Copyright IBM Corp 1995 1999 487 Killed To minimize paging space problems do any of the following and recompile your program e Reduce the size of your program by splitting it into two or more source files e Compile your program without optimization e Reduce the number of processes competing for system paging space e Increase the sys
603. the RISC System 6000 system The table below summarizes alignment information for each type te T S long double halfword aligned quadrupleword with qlongdouble or qldbl128 option Example The following example uses these symbols to show padding and boundaries p padding halfword boundary byte boundary For pragma options align mac68k struct A char a sizeof A The layout of A is a p For 440 C for AIX Users Guide pragma options align mac68k struct B char a double b sizeof B 10 The layout of B is a p b b b b b b b b Bit fields for Macintosh Format The following rules apply when you are laying out bit fields in structures An individual bit field can be at most 32 bits long Bit fields are packed into a word and are aligned on a 2 byte boundary Bit fields that would cross a word boundary are moved to the next halfword boundary even if they are already starting on a halfword boundary The bit field may still end up crossing a word boundary A bit field of width zero forces the next member even if it is not a bit field to start at the next halfword boundary even if the zero width bit field is currently at a halfword boundary A structure containing nothing but zero width bit fields is allowed and will have a length in bytes of two times the number of zero width bit fields For unions there is one special case Unions whose largest element is a bit fiel
604. the flttrap option with no suboptions is equivalent to setting qflttrap ov und zero inv inex The exceptions are not automatically enabled and all floating point operations are checked to provide precise exception location information If your program contains signalling NaNs you should use the qfloat nans along with qflttrap to trap any exceptions The compiler exhibits behavior as illustrated in the following examples when the qflttrap option is specified together with qoptimize options e with O 1 0 generates a divO exception and has a result of infinity 0 0 generates an invalid operation e with O3 1 0 generates a divO exception and has a result of infinity 0 0 returns zero multiplied by the result of the previous division Example To compile myprogram c so that floating point overflow and underflow and divide by zero are detected enter xlc myprogram c qflttrap overflow underflow zerodivide enable Related Reading fold Option Type Default Value pragma options Syntax qfold qnofold FOLD NOFOLD Appendix A Compiler Options 265 Purpose Specifies that constant floating point expressions are to be evaluated at compile time Notes This option is obsolete Use qfloat fold in your new applications Related Reading fullpath Option Type Default Value pragma options Syntax qfullpath qnofullpath Purpose Specifies what path information is stored for files when you use the
605. the smallest enclosing do for switch or while statement In a switch body the break passes control out of the switch body to the next statement outside the switch body Chapter 6 The C Language 145 Restrictions A break statement can appear only in the body of an iterative statement or a switch statement Related Reading Examples Using the break Statement The following example shows a break statement in the action part of a for statement If the ith element of the array string is equal to 0 the break statement causes the for statement to end for 1 0 1 lt 5 TH if stringLi 0 break lengtht The following is an equivalent for statement if string does not contain any embedded null characters for i 0 i lt 5 amp amp stringli O i lengtht The following example shows a break statement in a nested iterative statement The outer loop goes through an array of pointers to strings The inner loop examines each character of the string When the break statement is processed the inner loop ends and control returns to the outer loop TRR xx This program counts the characters in the strings that are xx part of an array of pointers to characters The count stops xx when one of the digits 0 through 9 is encountered xx and resumes at the beginning of the next string k k j include lt stdio h gt define SIZE 3 int main void static char strings SIZE ab c5d e
606. therefore be parallelized Specifies the approximate number of loop iterations for the chosen loop Explicitly instructs the compiler to parallelize the chosen loop Asserts that specified arrays in the chosen loop contain no repeated values Specifies scheduling algorithms for parallel loop execution Explicitly instructs the compiler to execute the chosen loop sequentially Defines a parallel region to be run by multiple threads in parallel With specific exceptions all other OpenMP directives work within parallelized regions defined by this directive Work sharing construct identifying an iterative for loop whose iterations should be run in parallel Shortcut combination of omp parallel and omp for pragma directives used to define a parallel region containing a single for directive Copyright IBM Corp 1995 1999 381 Work sharing construct identifying a non iterative section of code containing one or more subsections of code that should be run in parallel Shortcut combination of omp parallel and omp sections pragma directives used to define a parallel region containing a single sections directive Work sharing construct identifying a section of code that must be run by a single available thread Synchronization construct identifying a section of code that must be run only by the master thread Synchronization construct identifying a statement block that must be executed by a single thread at a time Synchronizes a
607. theses The following example shows the values of a b and the result of a b represented as 32 bit binary numbers bit pattern of a 00000000000000000000000001011100 bit pattern of b 00000000000000000000000000101110 bit pattern of a b 00000000000000000000000001111110 Note The bitwise OR should not be confused with the logical OR operator For example 1 4 evaluates to 5 while 1 4 evaluates to 1 amp amp Logical AND The amp amp logical AND operator indicates whether both operands have a nonzero value If both operands have nonzero values the result has the value 1 Otherwise the result has the value 0 Both operands must have a scalar type The usual arithmetic conversions on each operand are performed The result has type int and is not an Ivalue Unlike the amp bitwise AND operator the amp amp operator guarantees left to right evaluation of the operands If the left operand evaluates to 0 the right operand is not evaluated The following examples show how the expressions that contain the logical AND operator are evaluated Expression Result 1 amp 0 0 1 amp 4 1 0 amp 0 0 The following example uses the logical AND operator to avoid division by zero y 0 amp amp x y The expression x y is not evaluated when y 0 evaluates to O Note The logical AND amp amp should not be confused with the bitwise AND amp operator For example 1 amp amp 4 evaluates to 1 whil
608. tifiers used as structure or member names can be redefined to represent different objects in the same scope without conflicting You cannot use the name of a member more than once in a structure type but you can use the same member name in another structure type that is defined within the same scope You cannot declare a structure type that contains itself as a member but you can declare a structure type that contains a pointer to itself as a member Defining a Structure Variable A structure variable definition contains an optional storage class keyword the struct keyword a structure tag a declarator and an optional identifier The structure tag indicates the data type of the structure variable Chapter 6 The C Language 95 You can declare structures having any storage class Most compilers however treat structures declared with the register storage class specifier as automatic structures Initializing Structures The initializer contains an equal sign followed by a brace enclosed comma separated list of values You do not have to initialize all members of a structure The following definition shows a completely initialized structure struct address int street_no char xstreet_name char city char prov char postal code E static struct address perm_address 3 Savona Dr Dundas Ontario L4B 2A1 The values of perm_address are Member Value perm _address street_no 3 perm_address street_name addres
609. ting Environment Variables to Select 64 or 32 bit Compilation Modes Setting Parallel Processing Run time Options Setting Environment Variables for the Message and Help Files Setting Environment Variables in bsh ksh or sh Shells Setting Environment Variables in csh Shell Chapter 3 Using the C for AIX emer Compiler Modes Types of Input Files Types of Output Files Invoking the Compiler Invoking the Linkage Editor Compiler Options Specifying Compiler Options on a the Command Line Specifying Compiler Options in Your Program Source Files Specifying Compiler Options in a Configuration File Specifying Compiler Options for Architecture PA 32 or 64 bit t Compilation Compiler Message and Listing Information Compiler Listings Message Severity Levels and Compiler Response Compiler Return Codes Compiler Message Format Chapter 4 Advanced Compiler Usage Program Optimization with the C for AIX Compiler l Optimization Techniques Used by the C for AIX Compiler Special Handling of Math and String Library Functions Floating Point Operations with the C for AIX Compiler RISC System 6000 Floating Point Hardware Compile Time Floating Point Arithmetic Floating Point Compiler Options Rounding Mode Restrictions Creating and Using Precompiled Headers Minimizing the Size of Object Files Chapter 5 Program Parallelization IBM Directives m OpenMP Directives Countable Loops Reduction Operations i
610. ting binary expressions that depend on the order in which the compiler evaluates the operands 70 CG for AIX Users Guide Conditional Expressions Assignment Expressions Comma Expression Related Reading A conditional expressions is a compound expression that contains a condition operand7 an expression to be evaluated if the condition has a non zero value operand2 and an expression to be evaluated if the condition has the value 0 operands Conditional expressions have right to left associativity The left operand operand7 is evaluated first and then only one of the two remaining operands is evaluated If that Operand s expression contains or returns arithmetic types the usual arithmetic conversions are performed on that expression s values An assignment expression stores a value in the object designated by the left operand There are two types of assignment operators simple assignment and compound assignment The left operand in all assignment expressions must be a modifiable lvalue The type of the expression is the type of the left operand The value of the expression is the value of the left operand after the assignment completes The result of an assignment expression is not an lvalue All assignment operators have the same precedence and have right to left associativity A comma expression contains two operands separated by a comma Although the compiler evaluates both operands the value of the right operand i
611. ting files such as lst files Example To preview the steps for the compilation of the source file myprogram c enter xlc myprogram c Related Reading 32 64 Option Type Default Value pragma options e E Syntax q32 q64 Purpose Selects either 32 or 64 bit compiler mode Notes The q32 and q64 options override the compiler mode set by the value of the OBJECT_MODE environment variable if it exists If the q32 and q64 options are not specified and the OBJECT MODE environment variable is not set the compiler defaults to 32 bit output mode If the compiler is invoked in in 64 bit mode the _ 64BIT____ preprocessor macro is defined Appendix A Compiler Options 231 Use q32 and q64 options along with the qarch and qtune les options to optimize the output of garch and qtune compiler options If specified alone without accompanying qarch and qtune compiler options the C for AIX compiler treats e q32 as qarch com q32 e q64 as qarch com q64 Example To specify that the executable program testing compiled from myprogram c is to run on a computer with a 32 bit PowerPC architecture enter xlc o testing myprogram c q32 qarch ppc Important Notes 1 If you mix 32 and 64 bit compilation modes your XCOFF objects will not bind You must recompile completely to ensure that all objects are in the same mode 2 Your link options must reflect the type of objects you are linking If you comp
612. tions marked with these keywords regardless of other qinline option settings To maximize inlining specify optimization O and also specify the qinline option qinline The compiler attempts to inline all appropriate functions with 20 executable source statements or fewer subject to any other settings of the suboptions to the qinline option If qinline is specified last all functions are inlined qnoinline Does not inline any functions If qnoinline is specified last no functions are inlined qinline threshold Sets a size limit on the functions to be inlined The number of executable statements must be less than or equal to threshold for the function to be inlined threshold must be a positive integer The default value is 20 Specifying a threshold value of 0 causes no functions to be inlined except those functions marked with the __inline Inline or _inline keywords The threshold value applies to logical C statements Declarations are not counted as you can see in the example below increment int a b i for i 0 i lt 10 i statement 1 a i statement 2 b i statement 3 qinline names The compiler does not inline functions listed by names Separate each name with a colon All other appropriate functions are inlined The option implies qinline For example qinline salary taxes expenses benefits causes all functions except those named salary taxes expenses or benefits to
613. tomatic storage duration An flush directive is implied with the following directives e omp barrier Entry to and exit from omp critical e Exit from omp parallel e Exit from omp for Exit from omp sections e Exit from omp single The omp flush directive must appear within a block or compound statement For example if x 0 pragma omp flush valid usage x if x 0 pragma omp flush invalid usage 398 C for AIX User s Guide Related Reading pragma omp ordered Preprocessor Directive The omp ordered directive identifies a structured block of code that must be executed in sequential order Syntax pragma omp ordered statement_block Notes The omp ordered directive must be used as follows e It must appear within the extent of a omp for or omp parallel for construct containing an ordered clause e It applies to the statement block immediately following it Statements in that block are executed in the same order in which iterations are executed in a sequential loop e An iteration of a loop must not execute the same omp ordered directive more than once e An iteration of a loop must not execute more than one distinct omp ordered directive Related Reading pragma omp threadprivate Preprocessor Directive The omp threadprivate directive defines the scope of selected file scope data variables as being private to a thread but file scope visible within that thread Syntax pragma omp th
614. tr _umalloc myheap 100000 _ufree ptr destroy user heap if _udestroy myheap _FORCE return 3 return initial block used to create heap free initial_ block return 0 Related Reading Example of Creating and Using a Shared Memory User Heap The following program shows how you might implement a heap shared between a parent and several child processes Example of a User Heap Parent Process page Lot shows the parent process which creates the shared heap First the main program calls the init function to allocate shared memory from the operating system using CreateFileMapping and name the memory so that other processes can use it by name The init function then creates and opens the heap The loop in the main program performs operations on the heap and also starts other processes The program then calls the term function to close and destroy the heap Example of a Shared User Heap Child Process page H93 shows the process started by the loop in the parent process This process uses OpenFileMapping to access the shared memory by name then extracts the heap handle for the heap created by the parent process The process then opens the heap makes it the default heap and performs some operations on it in the loop After the loop the process replaces the old default heap closes the user heap and ends Example of a User Heap Parent Process The following program shows how you might implement a heap sh
615. truct union and enum type definitions are included for debugger processing Notes Use this option with the g option to produce additional debugging information When you specify the g option debugging information is included in the object file To minimize the size of object and executable files the compiler only includes information for symbols that are referenced Debugging information is not produced for unreferenced arrays pointers or file scope variables unless qdbxextra is specified Using qdbxextra may make your object and executable files larger Example To include all symbols in myprogram c for debugger processing enter xlc myprogram c g qdbxextra Related Reading digraph Option Type Default Value pragma options Syntax qdigraph qnodigraph Purpose Lets you use digraph character sequences to represent characters not found on some keyboards Digraphs are enabled by default Example To disable digraph character sequences when compiling your program enter xlc myprogram c qnodigraph 252 C for AIX User s Guide Related Reading dollar Option Type Default Value pragma options fp saoption foster Syntax qdollar qnodollar Purpose Allows the symbol to be used in the names of identifiers Example To compile myprogram c so that is allowed in identifiers in the program enter xlc myprogram c qdollar Related Reading Option Type Default Value pragma options a a
616. tructures Bit fields have the following alignment properties under the twobyte and packed suboptions Chapter 6 The C Language 99 twobyte Bit fields are packed into a word and are aligned on a halfword boundary Bit fields cannot cross word boundaries but are forced to start at the next halfword boundary even if they start on a halfword boundary A bit field with a width of O zero forces the next member to start at the next halfword boundary even if it is not a bit field and even if the zero width bit field is already at a halfword boundary A structure containing nothing but zero width bit fields has a length equal to twice the number of zero width bit fields In the following example the bit fields in the structure species are aligned according to the qalign twobyte option pragma options align twobyte struct species char a int D int b 4 int c 18 8 8 2 bits ie The following figure shows the layout of species The shaded areas are padding Byte Count 1 2 3 4 5 6 F foie byby e e Py Bit field b starts on a halfword boundary because of the unnamed zero width int bit field It occupies the first 4 bits of the third byte byte 2 in the figure Because bit field c is larger than 2 bytes it cannot cross the word boundary between bytes 3 and 4 but is forced to start at byte 4 It occupies bytes 4 and 5 the first two bytes of the second word and 2 bits of byte 6 100 C for AIX User s Guid
617. tters in identifiers Fortran and Pascal use only lowercase letters for all external names Both fold external identifiers to lowercase by default e Avoid using the underscore _ and dollar sign as the first character in identifiers to prevent conflict with the naming conventions for the C language library e Avoid using long identifier names The maximum number of significant characters in identifiers is 250 characters Related Reading Corresponding Data Types The following table shows the correspondence between the data types available in C for AIX C Set for AIX Fortran and Pascal Several data types in C have no equivalent representation in Pascal or Fortran Do not use them when programming for interlanguage calls Blank table cells indicate that no matching data type exists Correspondence of Data Types among C C Fortran and Pascal C and C Data Types Fortran Data Types Pascal Data Types CHARACTER CHAR INTEGER 1 PACKED 128 127 BYTE LOGICAL 1 PACKED 0 255 eama CSS Copyright IBM Corp 1995 1999 207 float REAL SHORTREAL REAL 4 double REAL 8 REAL DOUBLE PRECISION long double REAL 8 REAL DOUBLE PRECISION long double with qlongdouble or REAL 16 qidbl128 structure of two floats COMPLEX RECORD of two SHORTREALS COMPLEX 4 structure of two doubles COMPLEX 16 RECORD of two REALS DOUBLE COMPLEX avictue of wo ong doubies COMPLEXS SSS suc SS d SS RE etes ow Specia
618. turns a pointer to dest Example This example contains a programming error The count specified on memmove is 15 instead of 5 and the memmove operation copies bytes past the end of the allocated object include lt stdlib h gt include lt string h gt include lt stdio h gt define SIZE 21 int main void char target p source target char malloc SIZE strcpy target a shiny white sphere p targett8 p points at the starting character of the word we want to replace source target 2 start of Shiny printf Before memmove target is s n target memmove p source 15 printf After memmove target becomes s n target return 0 Kk kkk kk K RRR kk kk kkk ER kkk RR ER ERR KERR ERK EKER kkk kkk EKER KERR RK ERK ERE RRR RE RRR ERK The output should be similar to Before memmove target is a shiny white sphere End of allocated object 0x00073c80 was overwritten at 0x00073c95 The first eight bytes of the memory block in hex are 61207368696E7920 This memory block was re allocated at line number 11 in memmove c Appendix F C for AIX Debug Functions 415 Heap state was valid at line 12 of memmove c Memory error detected at line 18 of memcpy c KARR KKK KKK RE KKK KK EK RRR KKK KEKE RRR KK ERK Kk Kk kkk ERK EKER Kk kkk kkk kkk kkk kkk kkkk Related Readin _debug memset Set Bytes to Value Format include lt string h gt void debug _memset void dest
619. type selections performed by the compiler with and without the longlit option in effect aaa Default 64 bit mode qlonglit option enabled unsuffixed decimal signed int signed long signed long unsigned long unsigned long unsuffixed octal or hex signed int signed long unsigned int unsigned long signed long unsigned long suffixed by u or U unsigned int unsigned long unsigned long suffixed by I or L signed long signed long unsigned long unsigned long suffixed by ul or UL unsigned long unsigned long Related Reading longlong Option Type Default Value pragma options Syntax qlonglong qnolonglong Purpose Allows long long integer types in your program Default The default with xic and cc is qlonglong which defines LONG_LONG long long types will work in C programs The default with c89 is qnolonglong long long types are ignored Example To compile myprogram c so that long long ints are not allowed enter xlc myprogram c qnolonglong Related Reading Appendix A Compiler Options 293 Option Type Default Value pragma options e Syntax M Purpose Creates an output file that contains targets suitable for inclusion in a description file for the AIX make command Notes The M option is functionally identical to the qmakedep option U files are not make files u files must be edited before they can be used with the make command For more information on this command see AIX Version 4 Comman
620. uding labels enumerators typedef names type names and template names e Identifiers that represent a function argument e Identifiers declared inside a block without the keyword extern Chapter 6 The C Language 55 Example of File and Function Prototype Visibility Scopes In the following example the variable x which is declared on line 1 is different from the x declared on line 2 The variable declared on line 2 has function prototype scope and is visible only up to the closing parenthesis of the prototype declaration Visibility of the variable x declared on line 2 resumes after the end of the prototype declaration 1 int x 4 variable x defined with file scope long myfunc int x long y variable x has function prototype scope 2 3 4 int main void 5 6 f ow BY 7 Related Reading Example of File and Block Visibility Scopes Functions with static storage class are visible only in the source file they are defined in All other functions can be globally visible The following program illustrates blocks nesting and scope The example shows two kinds of scope file and block The main function prints the values 1 2 3 0 3 2 1 on separate lines Each instance of i represents a different variable include lt stdio h gt int i 1 i defined at file scope int main int argc char argv i printf d n i Prints 1 int i 2 j 3 i and j defi
621. ug realloc returns NULL If not enough memory is available to expand the block to the given size the original block is unchanged and NULL is returned Example This example uses _debug_realloc to allocate 100 bytes of storage It then attempts to write to storage that was not allocated When _debug_realloc is called again heap check detects the error generates several messages and stops the program Note You must compile this example with the qheapdebug option to map the realloc calls to _debug_realloc include lt stdlib h gt include lt stdio h gt include lt string h gt int main void char ptr if NULL ptr char realloc NULL 100 puts Could not allocate memory block exit EXIT_FAILURE memset ptr a 105 overwrites storage that was not allocated ptr charx realloc ptr 200 realloc invokes _heap_check puts debug realloc did not detect that a memory block was overwritten return 0 418 C for AIX Users Guide kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk The output should be similar to End of allocated object 0x00073890 was overwritten at 0x000738f4 The first eight bytes of the memory block in hex are 6161616161616161 This memory block was re allocated at line number 8 in debug reall c Heap state was valid at line 8 of debug reall c Memory error detected at line 13 of debug reall c KKK KKK KKK KERR KERR ERK kkkkkkkkkkkkkkkkkkkkkk
622. uide You should use the ansi language level for most new programs You can specify support for other language levels with the qlanglvl compiler option if your environment and applications require it The C for AIX compiler also uses various compiler invocation modes to provide additional support for specific environments and levels of the C language Related Reading Basic Data Types char char Use to declare arrays of characters pointers to characters and arrays of pointers to characters Signed char unsigned char Use to declare numeric variables that occupy a single byte To declare a data object having a character type use the char type specifier The char specifier has the form char identifier ed unsianec signer The declarator for a simple character declaration is an identifier You can initialize a simple character with a character constant or with an expression that evaluates to an integer The C language has three character data types char signed char and unsigned char These data types are not compatible with each other but each provides enough storage to hold any member of the ASCII character set The amount of storage allocated for a char is implementation dependent The C for AIX compiler uses 8 bits to represent a character as defined by the CHAR_BIT macro in the lt limits h gt header The default character type behaves like an unsigned char To change this default use pragma chars or the qch
623. unction scope static and extern declarations can be initialized with the address of a previously defined static or extern In a file scope data definition the initializer must evaluate to a constant or to the address of a static storage extern or static object plus or minus an integer constant that is defined or declared earlier in the file The constant expression in the initilizer can contain integer character enumeration or float constants casts to any type sizeof expressions and unary address expressions The following show constants used in expressions Expression Containing Constant Constant x 42 42 extern int cost 1000 1000 y 3 29 3 29 Related Reading Function Calls A function call is a primary expression containing a simple type name and a parenthesized argument list The argument list can contain any number of expressions separated by commas It can also be empty For example stub overdue account date amount notify name date 5 report error time date num The arguments are evaluated and each formal parameter is assigned the value of the corresponding argument Assigning avalue to a formal parameter within the function body changes the value of the parameter within the function but has no effect on the argument The type of a function call expression is the return type of the function The return value is determined by the return statement in the function definition The result of a
624. unctions or when you call functions through a pointer Therefore the qinlglue option only affects function calls through pointers or calls to an external compilation unit For calls to an external function you should specify that the function is imported by using for example the qprocimported option The inlining of glue code can cause the size of code to grow This can be overridden by specifying the qcompact option thereby disabling the qinlglue option Related Reading inline Option Type Default Value pragma options aopton See boom Syntax Appendix A Compiler Options 2 7 qinline qinline threshold qinline names qinlinetnames qinline limit qnoinline Purpose Attempts to inline functions instead of generating calls to a function Inlining is performed if possible but depending on which optimizations are performed some functions might not be inlined Notes The qinline option is functionally equivalent to the Q option Because inlining does not always improve run time you should test the effects of this option on your code Do not attempt to inline recursive or mutually recursive functions Normally application performance is optimized if you request optimization O option and compiler performance is optimized if you do not request optimization The C for AIX _inline Inline and __inline language keywords override all qinline options except qnoinline The compiler will try to inline func
625. urrently the compiler gives out of range warning messages when attempting to assign a value larger than the designated range into a long type The warning message is 1506 207 W Integer constant 0x100000000 out of range Copyright IBM Corp 1995 1999 341 This warning message may not appear for every case When you bit left shift a 32 bit constant and assign it into a long type signed values are sign extended and unsigned values are zero extended The examples in the table below show the effects of performing a bit shift on both 32 and 64 bit constants using the following code segment long l constantL lt lt 1 Initial Constant Value Constant Value after Bit Shift Ox7FFFFFFEFL INT_MAX OxFFFFFFFE OxFFFFFFFE OxFFFFFFFFL UINT_MAX OxFFFFFFFE 0x1 FFFFFFFE Unsuffixed constants can lead to type ambiguity that can impact other parts of your program such as the result of sizeof operations For example in 32 bit mode the compiler types a number like 4294967295 UINT_ MAX as an unsigned long In 64 bit mode this same number becomes a signed long To avoid this possibility explicitly add a suffix to all constants that have the potential of impacting constant assignment or expression evaluation in other parts of your program The fix for the above case is to write the number as 4294967295U This forces the compiler to always see that constant as an unsigned int regardless of compiler mode Assignment of Long Variables to Integers
626. used than it is to experience cache misses or page faults from specifying a cache size larger than actually present The data cache has a greater effect on program performance than the instruction cache If you have limited time available to experiment with different cache configurations determine the optimal configuration specifications for the data cache first If you specify the wrong values for the cache configuration or run the program on a machine with a different configuration program performance may degrade but program output will still be as expected The O4 and O5 optimization options automatically select the cache characteristics of the compiling machine If you specify the qcache option together with the O4 or O5 options the option specified last takes precedence Examples 1 To tune performance for a system with a combined instruction and data level 1 cache where the cache is two way associative 8 KB in size and has 64 byte cache lines type xlc qipa qcache type c level 1 size 8 line 64 assoc 2 file c To tune performance for a system with two levels of data cache specify the qcache option once for each level of cache xlc 04 qcache type D level 1 size 256 1ine 256 assoc 4 qcache type D level 2 size 512 line 256 assoc 2 file c To tune performance for a system with two types of cache again specify the qcache option once for each type of cache xlc 05 qipa qcache type D 1evel 1 size 256 1ine 256 assoc 4
627. utomatic variables require storage only while they are actually being used defining variables with the auto storage class can decrease the amount of memory required to run a program However having many large automatic objects may cause you to run out of stack space 106 C for AIX User s Guide Declaring variables with the auto storage class can also make code easier to maintain because a change to an auto variable in one function never affects another function unless it is passed as an argument The following example lines declare variables having the auto storage class specifier auto int counter auto char letter k Initialization You can initialize any auto variable except parameters If you do not initialize an automatic object its value is indeterminate If you provide an initial value the expression representing the initial value can be any valid C expression For structure and union members the initial value must be a valid constant expression if an initializer list is used The object is then set to that initial value each time the program block that contains the object s definition is entered Note If you use the goto statement to jump into the middle of a block automatic variables within that block are not initialized Storage Objects with the auto storage class specifier have automatic storage duration Each time a block is entered storage for auto objects defined in that block is made available When the block
628. utside a function The defined object is accessible to all functions that follow the definition and are located within the same source file as the definition E file scope A name declared outside all blocks and classes has file scope and can be used after the point of declaration in a source file float constant A number containing a decimal point an exponent or both a decimal point and an exponent The exponent contains an e or E an optional sign or and one or more digits 0 through 9 for statement A looping statement that contains the word for followed by a list of expressions enclosed in parentheses the condition and a statement the action Each expression in the parenthesized list is separated by a semicolon You can omit any of the expressions but you cannot omit the semicolons function A named group of statements that can be invoked and evaluated and can return a value to the calling statement 492 C for AIX Users Guide function call An expression that moves the path of execution from the current function to a specified function and evaluates to the return value provided by the called function A function call contains the name of the function to which control moves and a parenthesized list of arguments function declarator The part of a function definition that names the function provides additional information about the return value of the function and lists the function parameters function definition Th
629. vironment variable is set to an absolute path otherwise you might run the application from the wrong directory so that it cannot locate the profile data files If that happens the program may not be optimized correctly or may be stopped by a segmentation fault A segmentation fault might also happen if you change the value of the PDFDIR variable and execute the application before finishing the PDF process Appendix A Compiler Options 309 Because this option requires compiling the entire application twice it is intended to be used after other debugging and tuning is finished as one of the last steps before putting the application into production Restrictions e Do not mix PDF files created by the current version of C for AIX with PDF files created by previous versions e PDF optimizations also require at least level 2 of O e The main program must be compiled with PDF for profiling to work properly If you want to use this option to optimize a library or other code that does not usually incorporate a main program supply a main program for the first PDF compilation then omit the main program for the second PDF compilation e Do not compile or run two different applications that use the same PDFDIR directory at the same time e You must use the same set of compiler options at all compilation steps for a particular program otherwise PDF cannot optimize your program correctly and may even slow it down All compiler settings must be the
630. xed With O2 certain optimizations are not performed because they may produce an incorrect sign in cases with a zero result and because they remove an arithmetic operation that may cause some type of floating point exception For example X 0 0 is not folded to X because under IEEE rules 0 0 0 0 0 0 which is X In some other cases some optimizations may perform optimizations that yield a zero result with the wrong sign For example X Y Z may result in a 0 0 where the original computation would produce 0 0 In most cases the difference in the results is not important to an application and O3 allows these optimizations Floating point expressions may be rewritten Computations such as a b c may be rewritten as a c b if for example an opportunity exists to get a common subexpression by such rearrangement Replacing a divide with a multiply by the reciprocal is another example of reassociating floating point computations Notes e qfloat fitint rsqrt are on by default in O3 e Built in functions do not change errno at O3 e Aggressive optimizations do not include the following floating point suboptions qfloat hsflt hssngl and qfloat rndsngl The default maxmem value is 1 at O3 e Refer to qflttrap to see the behavior of the compiler when you specify optimize options with the flttrap option e The O3 option implies qnostrict You can use the qstrict compiler option to turn resulting optimizations that c
631. y Table Primary Operators Unary Operators Binary Operators Conditional Operator 7 Assignment Operators Comma Operator Arithmetic Conversions Table Functions Function Declarations Function Definitions main Function Program Statement Keywords break continue do Expressions for goto if else Null Statement return switch while Statement Labels Statement Blocks Example of Initialization within Statement Blocks C Programming Character Set Escape Sequences for Non Printable Characters Reserved Keywords i Differences Between C Language Levels Conflicts Between extended C and Other Levels Extensions to RT C Provided by extended C Exceptions to ansi C Addressed by classic C saal2 C Deviations from SAA Level 2 C Arithmetic Conversions for extended Level C Summary of C Language Level Conflicts Chapter 7 Writing C Programs Creating and Naming a C Source File File Naming Conventions a Internal Structure of a C Program Example of a Simple C Program Example of a C Program Comprised of Two Source Files External Structure of a C Program Specifying Path Names for Include Files Using a Full Path Name to Imbed Files Using a Relative Path Name to Imbed Files Directory Search Sequence for Include Files Using Relative Path Names Using Memory Heaps in a Program Memory Management Functions Managing Memory with Multiple Se Types of Memory Debugging Memory Heaps m Cha
632. y from user created heaps that you specify If you want you can also explicitly specify the runtime heap The names of user created heaps are prefixed by _u for user heaps for example umalloc and they are defined in lt umalloc h gt When working with user created heaps you need to link to the libhu a library Heap specific functions provided in this library are e _ucalloc e _umalloc e _uheapmin There are no heap specific versions of realloc or free These standard functions always determine which heap memory is allocated from and can be used with both user created and runtime memory heaps Debug Functions Use these functions to allocate and free memory from the default runtime heap just as you would use the regular versions They also provide information that you can use to debug memory problems Use the qheapdebug compiler option to automatically map all calls to the regular memory management functions to their debug versions You can also call the debug versions explicitly Note If you parenthesize the calls to the regular memory management functions they are not mapped to their debug versions You should place a pragma strings readonly directive at the top of each source file that will call debug functions or in a common header file that each includes This directive is not essential but it ensures that the file name passed to the debug functions can t be overwritten and that only one copy of the file name
633. your source program This option only affects error messages that specify the column number at which an error occurred For example the compiler will consider tabs as having a width of one character if you specify qtabsize 1 In this case you can consider one character position where each character and each tab equals one position regardless of tab length as being equivalent to one character column Related Reading tbtable Option Type Default Value pragma options Syntax qtbtable suboption TBTABLE suboption Purpose Generates a traceback table that contains information about each function including the type of function as well as stack frame and register information The traceback table is placed in the text segment at the end of its code Notes Values for suboption are none No traceback table is generated The stack frame cannot be unwound full A full traceback table is generated complete with name and parameter information smal The traceback table generated has no name or parameter information but otherwise has full traceback capability The pragma options directive must be specified before the first statement in the compilation unit Default Many performance measurement tools require a full traceback table to properly analyze optimized code The etc vac cfg compiler configuration file contains entries to accomodate this requirement If you do not require full traceback tables for your optimized code you
Download Pdf Manuals
Related Search
Related Contents
G510 GPRS Module AT Command User Manual - Premier VSM GUI Getting Started Guide RS485 Communications Card "OPC-F1-RS" Electrónica Long Term Care Claims - Connecticut Medical Assistance Program User Manual Trust XpertTouch XL HP LC2640N Quick Setup Poster ターボポンプ動作確認チェックシート Copyright © All rights reserved.
Failed to retrieve file