HP C/HP-UX Reference Manual Version A.06.05 Edition 5 Manufacturing Part Number: B3901-90020 Septeember 2005 Printed in the U.S.A. © Copyright 2003-2004. Hewlett-Packard Development Company L.P..
Legal Notices Confidential computer software. Valid license from HP required for possession, use or copying. Consistent with FAR 12.211 and 12.212, Commercial Computer Software, Computer Software Documentation, and Technical Data for Commercial Items are licensed to the U.S. Government under vendor’s standard commercial license. The information contained herein is subject to change without notice.
Contents 1. What is HP C? ANSI Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Compatibility Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About HP C/HP-UX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HP C Online Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . long . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents String Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Structuring a C Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 3. Data Types and Declarations Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents Usual Arithmetic Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Arithmetic Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Integral Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Floating Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents Comma Operator (,) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents Arrays and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Casting a Pointer's Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Null Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Relational Operators (>, >=, <, ==, !=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . .
Contents Compound Statement or Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How the for Loop is Executed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . for Loop Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . for versus while Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . .
Contents Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 7. Preprocessing Directives Overview of the Preprocessor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Source File Inclusion (#include) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents 9. Compiling and Running HP C Programs Compiling HP C Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The cc(1) Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specifying Files to the cc Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specifying Options to the cc Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents HP_LONG_RETURN Pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . HP_NO_RELOCATION Pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Gather/Scatter Prefetch Pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Example: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Running HP C Programs . . . . . . . . . . . . . . . . . . . . . . .
Contents Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . String Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents xvi
About This Document This manual presents reference information on the C programming language, as implemented on Itanium- based systems. The document printing date and part number indicate the document’s current edition. The printing date will change when a new edition is printed. Minor changes may be made at reprint without changing the printing date. The document part number will change when extensive changes are made.
Related Documents The following is a list of documents available with this release: • HP aC++/HP ANSI C Release Notes • HP aC++/HP C Programmer’s Guide • HP C/HP-UX Reference Manual Additional information about the HP C compiler can be found at http://www.docs.hp.com in the Development Tools and Distributed Computing section.
HP Encourages Your Comments HP encourages your comments concerning this document. We are truly committed to providing documentation that meets your needs. Please send comments to: c++-editor@cup.hp.com Please include document title, manufacturing part number, and any comment, error found, or suggestion for improvement you have concerning this document.
xx
1 What is HP C? HP C originates from the C language designed in 1972 by Dennis Ritchie at Bell Laboratories. It descended from several ALGOL-like languages, most notably BCPL and a language developed by Ken Thompson called B. C has been called a low-level, high-level programming language. C's operators and data types closely match those found in modern computers. The language is concise and C compilers produce highly efficient code.
What is HP C? ANSI Mode ANSI Mode Unless you are writing code that must be recompiled on a system where ANSI C is not available, it is recommended that you use the ANSI mode of compilation for your new development. It is also recommended that you use ANSI mode to recompile existing programs after making any necessary changes.
What is HP C? Compatibility Mode Compatibility Mode You may not want to change your existing code, or you may have old code that relies on certain non-ANSI features. Therefore, a compatibility mode of compilation has been provided. In this mode, virtually all programs that compiled and executed under previous releases of HP C/HP-UX will continue to work as expected. In HP-UX 10.20 and earlier releases, compatibility mode is the default compilation mode. In HP-UX 10.
What is HP C? About HP C/HP-UX About HP C/HP-UX This manual presents ANSI C as the standard version of the C language. Where certain constructs are not available in compatibility mode, or would work differently, it is noted and the differences are described. HP C/HP-UX, when invoked in ANSI mode, is a conforming implementation of ANSI C, as specified by American National Standard 9899-1990.
What is HP C? HP C Online Help HP C Online Help Online help for HP C is available for HP 9000 workstation and server users. HP C Online Help can be accessed from an HTML browser of your choice.
What is HP C? HP C Online Help Accessing HP C Online Help To access the HP C Online Help, you must be logged onto a system where the most recent version of the HP C compiler is installed. Typing the following at the command line invokes an HTML browser, which displays the main HTML index file for the HP C Online Help system: /opt/ansic/bin/cc +help The actual location of the HTML files is: file:/${CROOTDIR}/html/guide/${LOCALE}/c_index.html.
2 Program Organization This section describes the following topics: • “Lexical Elements” on page 8 • “Declarations” on page 18 • “Constants” on page 24 • “Structuring a C Program” on page 30 Chapter 2 7
Program Organization Lexical Elements Lexical Elements C language programs are composed of lexical elements. The lexical elements of the C language are characters and white spaces that are grouped together into tokens.
Program Organization Lexical Elements Comments A comment is any series of characters beginning with /* and ending with */. The compiler replaces each comment with a single space character. HP C allows comments to appear anywhere in the source file except within identifiers or string literals. The C language does not support nested comments. In the following example, a comment follows an assignment statement: average = total / number_of_components; /* Find mean value.
Program Organization Lexical Elements Legal Identifiers meters green_eggs_and_ham system_name UPPER_AND_lower_case $name Legal in HP C, but non-standard Illegal Identifiers 20_meters int no$#@good Starts with a digit The int type is a reserved keyword Contains illegal characters Length of Identifiers HP C identifiers are unique up to 256 characters. The ANSI/ISO standard requires compilers to support names of up to 32 characters for local variables and 6 characters for global variables.
Program Organization Lexical Elements Predefined identifier _func_ The HP ANSI C compiler defines the predefined identifier__func__, as specified in the C9X Standard. This provides an additional means of debugging your code. The use of the predefined "__func__" identifier allows you to use more informative debugging statements to indicate a specific function. This is useful for fatal errors and conditions that produce warnings.
Program Organization Lexical Elements • enum • extern • float • for • goto • if • int • long • register • return • short • signed • sizeof • static • struct • switch • __thread • typedef • union • unsigned • void • volatile • while auto Causes the variable to be dynamically allocated and initialized only when the block containing the variable is being executed. This is the default for local variables. break See “break” on page 156.
Program Organization Lexical Elements case An optional element in a switch statement. The case label is followed by an integral constant expression and a (:) colon. No two case constant expressions in the same switch statement can have the same value. For example: switch (getchar()) { case 'r': case 'R': moveright(); break; ... } char The char keyword defines an integer type that is 1 byte long. A char type has a minimum value of -128 and a maximum value of 127.
Program Organization Lexical Elements default: printf("Invalid grade\n"); break; } do See “do…while” on page 159. double A 64-bit data type for representing floating-point numbers. The lower normalized bound is 2.225E-308. The lower de normalized bound is 4.941E-324. The upper bound is 1.798E+308. Other floating-point types are float and long double. else See “if” on page 169. enum See “Enumeration” on page 52.
Program Organization Lexical Elements goto See “goto” on page 166. if See “if” on page 169. int A 32-bit data type for representing whole numbers. The range for int is -2,147,483,648 through 2,147,483,647. The range for unsigned int is 0 through 4,294,967,295. long A 32-bit integer data type in the HP-UX 32-bit data model. The range for long is -2,147,483,648 through 2,147,483,647. For the HP-UX 64-bit data model, the long data type is 64-bits and the range is the same as the long long data type.
Program Organization Lexical Elements • char • int • enum • long • long long • short Whether or not char is signed or unsigned by default is implementation-defined. The signed keyword lets you explicitly declare (in a portable) way a signed char. sizeof See “sizeof Operator” on page 131. static A variable that has memory allocated for it at program startup time. The variable is associated with a single memory location until the end of the program.
Program Organization Lexical Elements Semantics for the __thread keyword: Only variables of static duration can be thread specific. Thread specific data objects can not be initialized. Pointers of static duration that are not thread specific may not be initialized with the address of a thread specific object — assignment is okay. All global variables, thread specific or not, are initialized to zero by the linker implicitly.
Program Organization Declarations void The void data type has three important purposes: • To indicate that a function does not return a value • To declare a function that takes no arguments • To allow you to create generic pointers. To indicate that a function does not return a value, you can write a function definition such as: void func(int a, int b) { . . . } This indicates that the function func() does not return a value.
Program Organization Declarations initial_value is an optional initializer for the variable.
Program Organization Declarations Improving Portability Type definitions can be used to compensate for differences in C compilers. For example: #if SMALL_COMPUTER typedef int SHORTINT; typedef long LONGINT; #elif BIG_COMPUTER typedef short SHORTINT; typedef int LONGINT; #endif This is useful when writing code to run on two computers, a small computer where an int is two bytes, and a large computer where an int is four bytes.
Program Organization Declarations Using typedefs for Arrays The following two examples illustrate what can happen when you mix pointers and typedefs that represent arrays. The problem with the program on the left is that ptr points to an array of 80 chars, rather than a single element of a char array. Because of scaling in pointer arithmetic, the increment operator adds 80 bytes, not one byte, to ptr.
Program Organization Declarations Table 2-2 Name Spaces (Continued) Name Spaces Description Goto Labels Names that mark the target of a goto statement. Function, Variable and All Other Names Any name that is not a member of the preceding three classes. NOTE The separate name spaces for goto labels and for each struct, union, or enum definition are part of the ANSI/ISO standard, but not part of the K&R language definition.
Program Organization Declarations Macro Names Macro names do interfere with the other four name spaces. Therefore, when you specify a macro name, do not use this name in one of the other four name spaces. For example, the following program fragment is incorrect because it contains a macro named square and a label named square: #define square(arg) arg * arg int main(void) { ... square: ...
Program Organization Constants Constants There are four types of constants in C: • Integer Constants • Floating-Point Constants • Character Constants • String Constants Every constant has two properties: value and type. For example, the constant 15 has value 15 and type int. Integer Constants HP C supports three forms of integer constants: decimal One or more digits from 0-9. The constant must not start with a 0. octal One or more digits from 0-7. The constant must begin with 0.
Program Organization Constants Table 2-3 Convention Summary (Continued) Constant Assigned Data Type both letters u or U and ll or LL suffix: unsigned long long Integer constants may not contain any punctuation such as commas or periods.
Program Organization Constants You may precede a floating-point constant with the unary plus or minus operator to make its value positive or negative. Scientific Notation Scientific notation is a useful shorthand for writing lengthy floating-point values. In scientific notation, a value consists of two parts: a number called the mantissa followed by a power of 10 called the characteristic (or exponent). The letter e or E, standing for exponent, is used to separate the two parts.
Program Organization Constants Character Constants A character constant is any printable character or legal escape sequence enclosed in single quotes. A character constant can begin with the letter L to indicate that it is a wide character constant; this notation is ordinarily used for characters in an extended character set. In HP C, an ordinary character constant occupies one byte of storage; a wide character constant occupies the rightmost byte of a 4-byte integer.
Program Organization Constants represent the null character as \0. This is exactly equivalent to the numeric constant zero (0). When you use the octal format, you do not need to include the zero prefix as you would for a normal octal constant. Multi-Character Constants Each character in an ordinary character constant takes up one byte of storage; therefore, you can store up to a 4-byte character constant in a 32-bit integer and up to a 2-byte character constant in a 16-bit integer.
Program Organization Constants Figure 2-1 0 A String Constants 1 2 3 4 5 6 s h o r t 7 8 9 10 11 12 13 14 s t r i n g \0 Like a character constant, a string constant can begin with the letter L to indicate that it is a string constant in an extended character set. To span a string constant over more than one line, use the backslash character (\), also called the continuation character.
Program Organization Structuring a C Program Structuring a C Program When you write a C program, you can put all of your source code into one file or spread it across many files. A typical C source file contains some or all of the following components: • Preprocessor directives • Variables • Functions Example 2-1 Example The following shows how a program can be organized: /* preprocessor directives */ #include #define WEIGHTING_FACTOR 0.
Program Organization Structuring a C Program /* start of function body */ { /* local variable declarations */ float value1, value2, result; /* statements */ printf("Enter two values -- "); scanf("%f%f", &value1, &value2); result = average(value1, value2); /* continuation line */ printf("The weighted average using a correction \ factor of %4.2f is %5.
Program Organization Structuring a C Program 32 Chapter 2
3 Data Types and Declarations In C, as in many other programming languages, you must usually declare identifiers before you can use them. The declarable entities in C are: • Objects • Functions • Tags and members of structures, unions, and enumerated types • Type definition names This chapter describes declarations, type specifiers, storage-class specifiers, structure and union specifiers, enumerations, declarators, type names, and initialization.
Data Types and Declarations Program Structure Program Structure A translation unit consists of one or more declarations and function definitions. Syntax translation-unit ::= external-declaration translation-unit external-declaration external-declaration ::= function-definition declaration Description A C program consists of one or more translation units, each of which can be compiled separately.
Data Types and Declarations Declarations Declarations A declaration specifies the attributes of an identifier or a set of identifiers.
Data Types and Declarations Declarations New Declaration Features HP C has added the C9x feature which allows you to declare variables and types inside a block of statements. This also allows declaration of new variables or types, such as expr_1, as shown in the for statement below: for(expr_1;expr_2;expr_3) statement_1 This new variable or type declared in expr_1 can be used in expr_2, expr_3 and statement_1.
Data Types and Declarations Declarations Examples Valid Declarations: extern int pressure [ ]; extern int lines = 66, pages; /* size will be declared elsewhere */ /* declares two variables, initializes the first one */ static char private_func (float); /* a function taking a float, returning a char, not known outside this unit */ const float pi = 3.
Data Types and Declarations Storage-Class Specifiers Storage-Class Specifiers A storage-class specifier is one of several keywords that determines the duration and linkage of an object. Syntax storage-class ::= typedef extern static auto register Description You can use only one storage-class specifier in a declaration. The typedef keyword is listed as a storage-class specifier because it is syntactically similar to one. The keyword extern affects the linkage of a function or object name.
Data Types and Declarations Storage-Class Specifiers If no storage class is specified and the declaration appears in a block, the compiler defaults the storage duration for an object to automatic. If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the extern storage-class specifier.
Data Types and Declarations Type Specifiers Type Specifiers Type specifiers indicate the format of the storage associated with a given data object or the return type of a function. Syntax type-specifier ::= char short int long long long unsigned signed float double void _Bool _Complex _Imaginary struct-or-union-specifier enum-specifier typedef-name Description Most of the type specifiers are single keywords. (Refer to Chapter 10, “HP C/HP-UX Implementation Topics,” on page 235 for sizes of types.
Data Types and Declarations Type Specifiers Table 3-1 C Type Specifiers (Continued) unsigned char short, signed short, short int, or signed short int unsigned short, or unsigned short int int, signed, signed int, or no type specifiers unsigned, or unsigned int long, signed long, long int, or signed long int long long, signed long long, long long int, or signed long long int unsigned long, or unsigned long int unsigned long long, or unsigned long long int float double long double _Bool float_Complex double
Data Types and Declarations _Bool _Bool This release supports the boolean data type _Bool. The variables of the data type _Bool can only have values true(1) or false(0), where true and false are preprocessor macros defined in the header file stdbool.h. The _Bool data type is a part of C99 standard (ISO/IEC 9899:1999). The C99 standard specifies boolean bitfields.
Data Types and Declarations _Bool • A bit field of type _Bool may be used in an expression where an int or unsigned int is used. • When a scalar value is converted to _Bool the result is 0, if the value compares equal to 0, else the result is 1. Rules for _Bool Conversion The following conversion rules are applicable while using _Bool. Scalar to _Bool Boolval = scalarval ? true : false; Boolval would be true(1) or false(0) depending whether scalarval is nonzero or zero.
Data Types and Declarations HP-Specific Type Qualifiers HP-Specific Type Qualifiers Syntax type-qualifier ::= __thread Description Beginning with the HP-UX 10.30 operating system release, the __thread keyword defines a thread-specific data variable, distinguishing it from other data items that are shared by all threads. With a thread-specific data variable, each thread has its own copy of the data item.
Data Types and Declarations Type Qualifiers Type Qualifiers Syntax type-qualifier :: = const volatile __restrict (or restrict for C99) Description This section describes the type qualifiers — volatile, const and __restrict (or restrict for C99). The volatile type qualifier directs the compiler not to perform certain optimizations on an object because that object can have its value altered in ways beyond the control of the compiler.
Data Types and Declarations Type Qualifiers The formal definition of restricted pointer in C99 follows: 1. Let D be a declaration of an ordinary identifier that provides a means of designating an object P as a restrict-qualified pointer to type T. 2. If D appears inside a block and does not have storage class extern, let B denote the block. If D appears in the list of parameter declarations of a function definition, let B denote the associated block.
Data Types and Declarations Type Qualifiers Table 3-2 Declarations using const and volatile (Continued) Declaration Meaning int *const const_ptr_to_int Declares a constant pointer to a variable int. int *volatile vpi, *pi; Declares two pointers: vpi is a volatile pointer to an int; pi is a pointer to an int. int const *volatile vpci; Declares a volatile pointer to a constant int. const *pci; Declares a pointer to a constant int. Since no type specifier was given, it defaults to int.
Data Types and Declarations Structure and Union Specifiers Structure and Union Specifiers A structure specifier indicates an aggregate type consisting of a sequence of named members. A union specifier defines a type whose members begin at offset zero from the beginning of the union.
Data Types and Declarations Structure and Union Specifiers Members are placed in physical storage in the same order as they are declared in the definition of the structure. A member's offset is the distance from the start of the structure to the beginning of the member. The compiler inserts pad bytes as necessary to insure that members are properly aligned.
Data Types and Declarations Structure and Union Specifiers separate name space reserved for tags. Thus, a structure tag may have the same spelling as a structure member or an ordinary identifier. Structure tags also obey the normal block scope associated with identifiers. Another tag of the same spelling in a subordinate block may hide a structure tag in an outer block.
Data Types and Declarations Structure and Union Specifiers Another use for structure tags is to write self-referential structures. A structure of type S may contain a pointer to a structure of type S as one of its members. Note that a structure can never have itself as a member because the definition of the structure's content would be recursive. A pointer to a structure is of fixed size, so it may be a member. Structures that contain pointers to themselves are key to most interesting data structures.
Data Types and Declarations Enumeration Enumeration The identifiers in an enumeration list are declared as constants. Syntax enum-specifier ::= [ type-specifier ] enum [ identifier ] {enumerator-list} [ type-specifier ] enum identifier enumerator-list ::= enumerator enumerator-list , enumerator enumerator ::= enumeration-constant enumeration-constant = constant-expression enumeration-constant ::= identifier Description The identifiers defined in the enumerator list are enumeration constants of type int.
Data Types and Declarations Enumeration enum color x, y[100]; In this example, the color enumeration tag declares two objects. The x object is a scalar enum object, while y is an array of 100 enums. An enumeration tag cannot be used before its enumerators are declared. Examples enum color {RED, GREEN, BLUE}; enum objectkind {triangle, square=5, circle}; /* circle == 6 */ Sized enum - HP C Extension By default, the HP C compiler on HP 9000 systems allocates four bytes for all enumerated variables.
Data Types and Declarations Declarators Declarators A declarator introduces an identifier and specifies its type, storage class, and scope.
Data Types and Declarations Declarators Description Various special symbols may accompany declarators. Parentheses change operator precedence or specify functions. The asterisk specifies a pointer. Square brackets indicate an array. The constant-expression specifies the size of an array. A declarator specifies one identifier and may supply additional type information.
Data Types and Declarations Declarators Array Declarators If D is a declarator, and T is some combination of type specifiers and storage class specifiers (such as int), then the declaration T D[constant-expression]; declares D to be an array of type T. You declare multidimensional arrays by specifying additional array declarators. For example, a 3 by 5 array of integers is declared as follows: int x[3][5]; This notation (correctly) suggests that multidimensional arrays in C are actually arrays of arrays.
Data Types and Declarations Declarators void clear(a, n) int a[]; int n; { while(n--) *a++ = 0; } /* has been converted to int * */ /* number of array elements to clear */ /* for the entire array */ /* clear each element to zero */ Variable Length Array Variable Length Array(VLA) is a part of C99 standards (ISO/IEC 9899:1999). VLA allows the integer expression delimited by [ and ] in an array declarator to be a variable expression or *.
Data Types and Declarations Declarators int (*x)[n]; int y[n]; }; // Error - x not ordinary identifier // Error - y not ordinary identifier } A goto statement is not allowed to jump past any declarations of identifiers having a VM type. A jump within the scope is permitted.
Data Types and Declarations Declarators If a function declarator is not part of a function definition, the optional identifier-list must be empty. Function declarators using prototype form are only allowed in ANSI mode. Functions can also return structures. If a function returns a structure as a result, the called function copies the resulting structure into storage space allocated in the calling function. The length of time required to do the copy is directly related to the size of the structure.
Data Types and Declarations Type Names Type Names A type name is syntactically a declaration of an object or a function of a given type that omits the identifier. Type names are often used in cast expressions and as operands of the sizeof operator.
Data Types and Declarations Type Definitions Using typedef Type Definitions Using typedef The typedef keyword, useful for abbreviating long declarations, allows you to create synonyms for C data types and data type definitions. Syntax typedef-name ::= identifier Description If you use the storage class typedef to declare an identifier, the identifier is a name for the declared type rather than an object of that type. Using typedef does not define any objects or storage.
Data Types and Declarations Type Definitions Using typedef Other type specifiers (that is, void, char, short, int, long, long long, signed, unsigned, float, or double) cannot be used with a name declared by typedef. For example, the following typedef usage is illegal: typedef long int li; . . . unsigned li x; typedef identifiers occupy the same name space as ordinary identifiers and follow the same scoping rules. Structure definitions which are used in typedef declarations can also have structure tags.
Data Types and Declarations Initialization Initialization An initializer is the part of a declaration that provides the initial values for the objects being declared. Syntax initializer ::= assignment-expression {initializer-list} {initializer-list , } initializer-list ::= initializer initializer-list , initializer Description A declarator may include an initializer that specifies the initial value for the object whose identifier is being declared.
Data Types and Declarations Initialization When initializing the members of an aggregate, the initializer is a brace-enclosed list of initializes. In the case of a structure with automatic storage duration, the initializer may be a single expression returning a type compatible with the structure. If the aggregate contains members that are aggregates, this rule applies recursively, with the following exceptions: • Inner braces may be optionally omitted.
Data Types and Declarations Initialization char *cp = "hello"; This declares the object cp as a character pointer initialized to point to the first character of the string “hello”. It is illegal to specify more initializes in a list than are required to initialize the specified aggregate. The one exception to this rule is the initialization of an array of characters with a string literal. char t[3] = "cat"; This initializes the array t to contain the characters c, a, and t.
Data Types and Declarations Initialization {1, 07, 03, 3.5, "cats eat bats" }, {2, 2, 4, 5.0, "she said with a smile"} }; Note that the object (s), being declared, is an array of structures without a specified dimension. The compiler counts the initializers to determine the array's dimension. In this case, the presence of two initializes implies that the dimension of s is two. You can initialize named bit-fields as you would any other member of the structure.
Data Types and Declarations Compound Literal Compound Literal Compound literal provide a mechanism for specifying constants of aggregate or union type. Compound literal is a part of the C99 standards (ISO/IEC 9899:1999: 6.5.2.5). Compound literals are an easy means of initializing an object of type aggregate or union without having to allocate a temporary variable for the object. It is represented as an unnamed object with a type and has an lvalue.
Data Types and Declarations Compound Literal Example 3-3 As a Parameter int main() { foo((int [])(1,2,3,4)); } int foo(int *p) { } In this example, a compound literal is passed as a parameter to function foo() instead of creating a temporary variable in the function main() and then passing the compound literal as a parameter to foo(). Compound literals can be passed as parameters to functions eliminating the need of defining a temporary variable in the caller function.
Data Types and Declarations Compound Literal This example is for structure objects created using compound literals, which are passed to functions. Example 3-9 Example 9: Possible Ways of Using Compound Literals int x = (int){5}; int *y = (int *){&x}; // initializing x with 5 // initializing y with address of x The purpose of the above example is only to show the other possible ways of using compound literals. NOTE Chapter 3 Compound literal is recognized only in the C99 mode (-AC99).
Data Types and Declarations Function Definitions Function Definitions A function definition introduces a new function. Syntax function-definition ::= [declaration-specifiers] declarator [declaration-list] compound-statement Description A function definition provides the following information about the function: 1. Type. You can specify the return type of the function. If no type is provided, the default return type is int.
Data Types and Declarations Function Definitions 3. Visibility outside defining translation unit. A function can be local to the translation unit in which it is defined (if the storage class specifier is static). Alternatively, a function can be visible to other translation units (if no storage class is specified, or if the storage class is extern). 4. Body of the function. You supply the body that executes when the function is called in a single compound statement following the optional declaration-list.
Data Types and Declarations Function Definitions Examples The following example shows a function that returns the sum of an array of integers.
Data Types and Declarations Function Definitions inline HP C supports inlining frequently used functions. These functions can be inlined by specifying them as inline either in the function declarator or in the function definition. NOTE inline is available only with -AC99. For all other options, you must use __inline. The optimizer uses its own heuristics to inline a function, if necessary. Examples The following examples detail the usage of inline.
Data Types and Declarations Four-Byte Extended UNIX Code (EUC) Four-Byte Extended UNIX Code (EUC) HP C/HP-UX supports four-byte Extended UNIX Code (EUC) characters in filenames, comments, and string literals.
4 Type Conversions The use of different types of data within C programs creates a need for data type conversions. For example, some circumstances that may require a type conversion are when a program assigns one variable to another, when it passes arguments to functions, or when it tries to evaluate an expression containing operands of different types. C performs data conversions in these situations. • Assignment — Assignment operations cause some implicit type conversions.
Type Conversions Integral Promotions Integral Promotions Wherever an int or an unsigned int may be used in an expression, a narrower integral type may also be used. The narrow type will generally be widened by means of a conversion called an integral promotion. All ANSI C compilers follow what are called value preserving rules for the conversion.
Type Conversions Integral Promotions To avoid situations where unsigned preserving and value preserving promotion rules yield different results, you could refrain from using an unsigned char or unsigned short in an expression that is used as an operand of one of the following operators: >>, /, %, <, <=, >, or >=. Or remove the ambiguity by using an explicit cast to specify the conversion you want.
Type Conversions Usual Arithmetic Conversions Usual Arithmetic Conversions In many expressions involving two operands, the operands are converted according to the following rules, known as the usual arithmetic conversions. The common type resulting from the application of these rules is also the type of the result. These rules are applied in the following sequence: 1. If either operand is long double, the other operand is converted to long double. 2.
Type Conversions Usual Arithmetic Conversions Step 3 does not apply, because in compatibility mode, whenever a float appears in an expression, it is immediately converted to a double. In step 4, remember that the integral promotions are performed according to the unsigned preserving rules when compiling in compatibility mode.
Type Conversions Arithmetic Conversions Arithmetic Conversions In general, the goal of conversions between arithmetic types is to maintain the same magnitude within the limits of the precisions involved. A value converted from a less precise type to a more precise type and then back to the original type results in the same value. Integral Conversions A particular bit pattern, or representation, distinguishes each data object from all others of that type.
Type Conversions Arithmetic Conversions Floating Conversions When an integer value is converted to a floating type, the result is the equivalent floating-point value. If it cannot be represented exactly, the result is the nearest representable value. If the two nearest representable values are equally near, the result is the one whose least significant bit is zero. When a long long is converted into a floating type, no overflow will occur but may result in loss of precision.
Type Conversions Arithmetic Conversions In most cases, when an expression with array type is used, it is automatically converted to a pointer to the first element of the array. As a result, array names and pointers are often used interchangeably in C. This automatic conversion is not performed in the following contexts: • When the array is the operand of sizeof or the unary &;. • It is a character string literal initializing an array of characters.
5 Expressions and Operators Operators are grouped as follows: • Arithmetic Operators (+, -, *, /, %) • Array Subscripting ([ ]) • Assignment Operators (=, +=, -=, *=, /=, %=,<<=, >>=, &=, ^=, |=) • Bit Operators (<<, >>, &, ^, |, ~) • Cast Operator • Comma Operator (,) • Conditional Expression Operator (?:) • Function Calls • Increment and Decrement Operators (++, --) • Logical Operators (&&, ||, !) • Pointer Operators (*, ->, &) • Relational Operators (>, >=, <, ==, !=) • sizeof Op
Expressions and Operators Arithmetic Operators (+, -, *, /, %) Arithmetic Operators (+, -, *, /, %) Syntax exp1 + exp2 Adds exp1 and exp2. An exp can be any integer or floating-point expression. exp1 - exp2 Subtracts exp2 from exp1. exp1 * exp2 Multiplies exp1 by exp2. exp1 / exp2 Divides exp1 by exp2. exp1 % exp2 Finds modulo of exp1 divided by exp2. (That is, finds the remainder of an integer division.) An expression can be any integer expression. -exp Negates the value of exp.
Expressions and Operators Arithmetic Operators (+, -, *, /, %) As required by the ANSI/ISO C standard, HP C supports the following relationship between the remainder and division operators: a equals a%b + (a/b) * b for any integer values of a and b The result of a division or modulo division is undefined if the right operand is 0. The sign reversal or unary minus operator (-) multiplies its sole operand by -1. For example, if x is an integer with the value -8, then -x evaluates to 8.
Expressions and Operators Array Subscripting ([ ]) Array Subscripting ([ ]) A postfix expression followed by the [ ] operator is a subscripted reference to a single element in an array. Syntax postfix-expression [ expression ] Description One of the operands of the subscript operator must be of type pointer to T (T is an object type), the other of integral type. The resulting type is T. The [ ] operator is defined so that E1[E2] is identical to (*((E1)+(E2))) in every respect.
Expressions and Operators Assignment Operators (=, +=, -=, *=, /=, %=,<<=, >>=, &=, ^=, |=) Assignment Operators (=, +=, -=, *=, /=, %=,<<=, >>=, &=, ^=, |=) Syntax lvalue = expression Simple assignment. lvalue += expression Addition and assignment. lvalue -= expression Subtraction and assignment. lvalue *= expression Multiplication and assignment. lvalue /= expression Division and assignment. lvalue %= expression Modulo division and assignment. lvalue <<= expression Left shift and assignment.
Expressions and Operators Assignment Operators (=, +=, -=, *=, /=, %=,<<=, >>=, &=, ^=, |=) x = 3; x = y; x = (y*z); /* assigns the value 3 to variable x /* assigns the value of y to x /* performs the multiplication and /* assigns the result to x */ */ */ */ An assignment expression itself has a value, which is the same value that is assigned to the left operand.
Expressions and Operators Assignment Operators (=, +=, -=, *=, /=, %=,<<=, >>=, &=, ^=, |=) The only internal difference between the two forms is that var is evaluated only once in the shorthand form. Most of the time this is not important; however, it is important when the left operand has side effects, as in the following example: int *ip; *ip++ += 1; *ip++ = *ip++ + 1; /* These two statements produce /* different results.
Expressions and Operators Assignment Operators (=, +=, -=, *=, /=, %=,<<=, >>=, &=, ^=, |=) assigns to j, the remainder of 71124 / (65535+1) The remainder is 5588. For non-negative numbers, and for negative numbers represented in two's complement notation, this is the same result that you would obtain by ignoring the extra bytes. Integer to Float Conversions You may assign an integer value to a floating-point variable. In this case, the integer value is implicitly converted to a floating-point type.
Expressions and Operators Assignment Operators (=, +=, -=, *=, /=, %=,<<=, >>=, &=, ^=, |=) This causes a loss of precision which could have a dramatic impact on your program. The same truncation process occurs for negative values. After the assignment j = -5.8; the value of j is -5. An equally serious situation occurs when the floating-point value cannot fit into an integer. For example: j = 999999999999.0 This causes an overflow condition which will produce unpredictable results.
Expressions and Operators Assignment Operators (=, +=, -=, *=, /=, %=,<<=, >>=, &=, ^=, |=) Floating-Point Overflows A serious problem occurs when the value being assigned is too large to be represented in the variable. For example, the largest positive number that can be represented by a float is approximately 3e38. However, neither the K&R language definition nor the ANSI/ISO C standard defines what happens if you try to make an assignment outside this range.
Expressions and Operators Bit Operators (<<, >>, &, ^, |, ~) Bit Operators (<<, >>, &, ^, |, ~) Syntax exp1 << exp2 Left shifts (logical shift) the bits in exp1 by exp2 positions. exp1 >> exp2 Right shifts (logical or arithmetic shift) the bits in exp1 by exp2 positions. exp1 & exp2 Performs a bitwise AND operation. exp1 ^ exp2 Performs a bitwise OR operation. exp1 | exp2 Performs a bitwise inclusive OR operation. ~exp1 Performs a bitwise negation (one's complement) operation.
Expressions and Operators Bit Operators (<<, >>, &, ^, |, ~) Shifting to the left is equivalent to multiplying by powers of two: x << y is equivalent to x * 2y. Shifting non-negative integers to the right is equivalent to dividing by powers of 2: x >> y is equivalent to x / 2y. The << operator always fills the vacated rightmost bits with zeros. If exp1 is unsigned, the >> operator fills the vacated leftmost bits with zeros.
Expressions and Operators Bit Operators (<<, >>, &, ^, |, ~) Table 5-1 Truth Table for the bitwise AND operator, (&) (Continued) bit x of op1 1 bit x of op2 1 bit x of result 1 The following table shows an example of the bitwise AND operator: Table 5-2 Expression The Bitwise AND Operator Hexadecimal Value Binary Representation 9430 0x24D6 00100100 11010110 5722 0x165A 00010110 01011010 9430 & 5722 0x0452 00000100 01010010 Bitwise Inclusive (|) OR The bitwise inclusive OR operator perform
Expressions and Operators Bit Operators (<<, >>, &, ^, |, ~) Bitwise exclusive OR (^) The bitwise exclusive OR operator performs logical operations on a bit-by-bit level using the following truth table: Table 5-5 Truth Table for the exclusive OR, ^ bit x of op1 bit x of op2 bit x of result 0 0 0 0 1 1 1 0 1 1 1 0 The bitwise exclusive OR (XOR) operator (^) sets a bit in the resulting value's bit position if either operand (but not both) has a bit set at the position.
Expressions and Operators Bit Operators (<<, >>, &, ^, |, ~) Table 5-8 Expression ~9430 Chapter 5 Example Using the Bitwise Complement Operator (Continued) Hexadecimal Value 0xdb29 Binary Representation 11011011 00101001 97
Expressions and Operators Cast Operator Cast Operator Syntax (data_type) exp Arguments data_type Any scalar data type, including a scalar data type created through a typedef. The data_type cannot be an aggregate type, but it can be a pointer to an aggregate type. exp Any scalar expression. Description To cast a value means to explicitly convert it to another data type.
Expressions and Operators Cast Operator Casting Integers to Other Integers It is possible to cast one integer into an integer of a different size and to convert a floating-point value, enumeration value or pointer to an integer.
Expressions and Operators Cast Operator unsigned char k = 37 (short) k => 0037 (int) k => 00000037 55 55 55 CASE C: Casting Integers to a Smaller Type When an int value is cast to a narrower type (short or char), the excess bits on the left are discarded. The same is true when a short is cast to a char, or when a long in 64-bit mode is cast to an int. For instance, if an int is cast to a short, the 16 leftmost bits are truncated. The following table of values illustrates these conversions.
Expressions and Operators Cast Operator Casting Floating-Point Values to Integers Casting floating-point values to integers may produce useless values if an overflow condition occurs. The conversion is made simply by truncating the fractional part of the number. For example, the floating-point value 3.712 is converted to the integer 3, and the floating-point value -504.2 is converted to -504. Here are some more examples: float f = 3.700, f2 = -502.2, f3 = 7.
Expressions and Operators Cast Operator int *int_p; float *float_p; struct S *str_p; extern foo(struct T *); . . . int_p = (int *) float_p; float_p = (float *) str_p; foo((struct T *) str_p); The cast is required whenever you assign a pointer value to a pointer variable that has a different base type, and when you pass a pointer value as a parameter to a function that has been prototyped with a different pointer type. The only exception to this rule concerns the generic pointer.
Expressions and Operators Comma Operator (,) Comma Operator (,) Syntax exp1, exp2 Arguments exp1 Any expression. exp2 Any expression. Description Use the comma operator to separate two expressions that are to be evaluated one right after the other. The comma operator is popular within for loops, as demonstrated by the following example: for (i = 10, j = 4; i * j < n; i++, j++); In the preceding example, the comma operator allows you to initialize both i and j at the beginning of the loop.
Expressions and Operators Conditional Expression Operator (?:) Conditional Expression Operator (?:) Syntax exp1 ? exp2 : exp3 Arguments exp1 Any expression. exp2 Any expression. exp3 Any expression. Description The conditional expression construction provides a shorthand way of coding an if…else condition.
Expressions and Operators Conditional Expression Operator (?:) Example /* Program name is "conditional_exp_op_example". This program uses the conditional expression to see if the user wants to continue adding numbers. */ #include
Expressions and Operators Function Calls Function Calls Syntax postfix-expression ( [argument-expression-list] ) Description Function calls provide a means of invoking a function and passing arguments to it. The postfix-expression must have the type “pointer to function returning T”. The result of the function will be type T. Functions can return any type of object except array and function. Specifically, functions can return structures.
Expressions and Operators Function Calls The compiler checks to see that there are as many arguments as required by the function prototype. If the prototype has an ellipsis, additional parameters are allowed. Otherwise, they are flagged erroneous. Also, the types of the arguments must be assignment-compatible with their corresponding formal parameters, or the compiler will emit a diagnostic message.
Expressions and Operators Function Calls Function Recursion All functions are recursive both in the direct and indirect sense. Function A can call itself directly or function A can call function B which, in turn, calls function A. Note that each invocation of a function requires program stack space. For this reason, the depth of recursion depends upon the size of the execution stack.
Expressions and Operators Increment and Decrement Operators (++, --) Increment and Decrement Operators (++, --) Syntax lvalue++ Increments the current value of lvalue after lvalue has been referenced. lvalue-- Decrements the current value of lvalue after lvalue has been referenced. ++lvalue Increments the current value of lvalue before lvalue is referenced. --lvalue Decrements the current value of lvalue before lvalue has been referenced.
Expressions and Operators Increment and Decrement Operators (++, --) You need to be careful, however, when you use the increment and decrement operators within an expression. Standalone Increment Decrement Expressions For example, as a stand-alone assignment or as the third expression in a for loop, the side effect is the same whether you use the prefix or postfix versions.
Expressions and Operators Increment and Decrement Operators (++, --) The C language does not specify which multiplication operand is to be evaluated first. One compiler may evaluate the left operand first, while another evaluates the right operand first. The results are different in the two cases.
Expressions and Operators Increment and Decrement Operators (++, --) #include int main(void) { int j = 5, k = 5, l = 5, m = 5; printf("j: %d\t k: %d\n", j++, k--); printf("j: %d\t k: %d\n", j, k); printf("l: %d\t m: %d\n", ++l, --m); printf("l: %d\t m: %d\n", l, m); } The result is as follows: j: j: l: l: 5 6 6 6 k: k: m: m: 5 4 4 4 The results show that the initial values of j and k are used in the first printf().
Expressions and Operators Logical Operators (&&, ||, !) Logical Operators (&&, ||, !) Syntax exp1 && exp2 Logical AND. exp1 || exp2 Logical OR. !exp1 Logical NOT. Arguments exp1 Any expression. exp2 Any expression. Description The logical AND operator (&&) and the logical OR (||) operator evaluate the truth or falsehood of pairs of expressions. The AND operator evaluates to 1 if and only if both expressions are true. The OR operator evaluates to 1 if either expression is true.
Expressions and Operators Logical Operators (&&, ||, !) Truth Table for C's Logical Operators In C, true is equivalent to any nonzero value, and false is equivalent to 0. The following table shows the logical tables for each operator, along with the numerical equivalent. All of the operators return 1 for true and 0 for false.
Expressions and Operators Logical Operators (&&, ||, !) Table 5-11 Examples of Expressions Using the Logical Operators Given the following declarations: int j = 0, m = 1, n = -1; float x = 2.5, y = 0.
Expressions and Operators Logical Operators (&&, ||, !) Example /* Program name is "logical_ops_example". This program /* shows how logical operators are used. #include */ */ int main(void) { int won_lottery, enough_vacation, money_saved; char answer; won_lottery = enough_vacation = money_saved = 0; printf("\nThis program determines whether you can "); printf("take your next vacation in Europe.
Expressions and Operators Logical Operators (&&, ||, !) printf("Look out Paris!\n"); else if (enough_vacation &&(!money_saved)) printf("You've got the time, but you haven't got \ the dollars.\n"); else if (!enough_vacation || (!money_saved)) { printf("Tough luck. Try saving your money and "); printf("vacation days next year.\n"); } /* end else/if */ } If you execute this program, you get the following output: This program determines whether you can take your next vacation in Europe.
Expressions and Operators Pointer Operators (*, ->, &) Pointer Operators (*, ->, &) Syntax *ptr_exp Dereferences a pointer. That is, finds the contents stored at the virtual address that ptr_exp holds. ptr->member Dereferences a ptr to a structure or union where member is a member of that structure or union. &lvalue Finds the virtual address where the lvalue stored. Description A pointer variable is a variable that can hold the address of an object.
Expressions and Operators Pointer Operators (*, ->, &) { int j = 1; int *pj; pj = &j; /* Assign the address of j to pj */ printf("The value of j is: %d\n", j); printf("The address of j is: %p\n", pj); } If you run this program (in 32-bit mode), the output looks something like this: The value of j is: 1 The address of j is: 7b033240 Dereferencing a Pointer To dereference a pointer (get the value stored at the pointer address), use the * operator.
Expressions and Operators Pointer Operators (*, ->, &) The expression *p_ch is interpreted as “Take the address value stored in p_ch and get the value stored at that address.” This gives us a new way to look at the declaration. The data type in the pointer declaration indicates what type of value results when the pointer is dereferenced. For instance, the declaration float *fp; means that when *fp appears as an expression, the result will be a float value.
Expressions and Operators Pointer Operators (*, ->, &) cc: "ptr_example3.c", line 9: warning 604: Pointers are not assignment-compatible. Pointer Arithmetic The following arithmetic operations with pointers are legal: • You may add an integer to a pointer or subtract an integer from a pointer. • You may use a pointer as an operand to the ++ and operators. • You may subtract one pointer from another pointer, if they point to objects of the same type.
Expressions and Operators Pointer Operators (*, ->, &) p1 = a; p2 = p1 + 4; j = p2 - p1; j = p1 - p2; p1 = p2 - 2; p3 = p1 - 1; j = p1 - p3; j = p1 + p2; /* /* /* /* /* /* /* /* Same as p1 = &a[0] */ legal */ legal -- j is assigned 4 */ legal -- j is assigned -4 */ legal -- p2 points to a[2] */ ILLEGAL -- different pointer types*/ ILLEGAL -- different pointer types*/ ILLEGAL -- cannot add pointers */ Arrays and Pointers Arrays and pointers have a close relationship in the C language.
Expressions and Operators Pointer Operators (*, ->, &) Null Pointers The C language supports the notion of a null pointer — that is, a pointer that is guaranteed not to point to a valid object. A null pointer is any pointer assigned the integral value 0. For example: char *p; p = 0; /* make p a null pointer */ In this one case — assignment of 0 — you do not need to cast the integral expression to the pointer type.
Expressions and Operators Pointer Operators (*, ->, &) { int count = 0; while (*arg++) count++; return count; } int main(void) { char a_word[30]; int number_of_characters; printf("Enter a word -- "); scanf("%s", a_word); number_of_characters = count_chars(a_word); printf("%s contains %d characters.\n", a_word, number_of_characters); } If you execute this program, you get the following output: Enter a word -- Marilyn Marilyn contains 7 characters.
Expressions and Operators Pointer Operators (*, ->, &) printf("%c", c1); printf("\n"); /* Print same name indirectly through an array of pointers. */ while (c2 = *(pstr[which_name]++)) printf("%c", c2); /* We could also have used the following statement instead of * the two previous ones: printf("%s", pstr[which_name]); */ printf("\n"); } If you execute this program, you get the following output: Which name do you want to retrieve? Enter 0 for the first name, 1 for the second name, etc.
Expressions and Operators Relational Operators (>, >=, <, ==, !=) Relational Operators (>, >=, <, ==, !=) Syntax exp1 > exp2 Greater than. exp1 >= exp2 Greater than or equal to. exp1 < exp2 Less than. exp1 <= exp2 Less than or equal to. exp1 == exp2 Equal to. exp1 != exp2 Not equal to. Arguments exp1 Any expression. exp2 Any expression. Description A relational expression consists of two expressions separated by one of six relational operators.
Expressions and Operators Relational Operators (>, >=, <, ==, !=) while (j == 5) do_something(); The first version is syntactically legal, since all expressions have a value. The value of the expression j = 5 is 5. Since this is a nonzero value, the while expression will always evaluate to true and do_something() will always be invoked. Relational Operators Precedence Rules Relational operators have lower precedence than arithmetic operators.
Expressions and Operators Relational Operators (>, >=, <, ==, !=) Evaluation of Relational Expressions Relational expressions are often called Boolean expressions, in recognition of the nineteenth-century mathematician and logician, George Boole. Many programming languages, such as Pascal, have Boolean data types for representing true and false. The C language, however, represents these values with integers. Zero is equivalent to false, and any nonzero value is considered true.
Expressions and Operators Relational Operators (>, >=, <, ==, !=) if (func()) proceed; else error handler; Dangers of Comparing Floating-Point Values You may get unexpected results if you compare floating-point values for equality because floating-point representations are inexact for some numbers. For example, the following expression, though algebraically true, will evaluate to false on many computers: (1.0/3.0 + 1.0/3.0 + 1.0/3.0) == 1.0 This evaluates to 0 (false) because the fraction 1.0/3.
Expressions and Operators Relational Operators (>, >=, <, ==, !=) Example 5-3 C’s Relational Operators in Action /* Program name is "relational_example". This program * does some mathematical calculations and shows * C's relational operators in action. */ #include
Expressions and Operators sizeof Operator sizeof Operator Syntax sizeof exp; sizeof (type_name) Arguments exp An expression of any type except function, void, or bit field. type_name The name of a predefined or user-defined data type, or the name of some variable. An example of a predefined data type is int. A user-defined data type could be the tag name of a structure. Description The sizeof unary operator finds the size of an object. It accepts two types of operands: an expression or a data type.
Expressions and Operators sizeof Operator sizeof x By convention, however, the parentheses are usually included. The operand can also be a data type, in which case the result is the length in bytes of objects of that type: sizeof(char) sizeof(short) sizeof(float) sizeof(int *) /* /* /* /* 1 2 4 4 on on on on all machines */ HP 9000 Series */ HP 9000 Series */ HP 9000 Series */ The parentheses are required if the operand is a data type.
Expressions and Operators sizeof Operator If you execute this program, you get the following output: TYPE SIZE char short int float double 1 2 4 4 8 Chapter 5 133
Expressions and Operators Structure and Union Members (., ->) Structure and Union Members (., ->) A member of a structure or a union can be referenced using either of two operators: the period or the right arrow. Syntax postfix-expression . identifier postfix-expression -> identifier Description Use the period to reference members of structures and unions directly. Use the arrow operator to reference members of structures and unions pointed to by pointers.
Expressions and Operators Operator Precedence Operator Precedence Precedence is the order in which the compiler groups operands with operators. The C compiler evaluates certain operators and their operands before others. If operands are not grouped using parentheses, the compiler groups them according to its own rules. The following lists C operator precedence in highest to lowest precedence: Table 5-14 C Operator Precedence Class of operator Operators Grouping primary () [] -> .
Expressions and Operators Operator Precedence Table 5-14 C Operator Precedence (Continued) Class of operator Operators conditional ?: assignment = /= &= comma , Grouping right to left += %= ^= -= >>= |= *= <<= right to left left to right Precedence among Operators of Same Class Most operators group from the left to the right but some group from the right to the left. The grouping indicates how an expression containing several operators of the same precedence will be evaluated.
Expressions and Operators Operator Quick Reference Operator Quick Reference Table 5-15 C Operators Symbol Meaning ! logical negation != inequality % remainder & AND (bitwise) and address-of && AND (logical) () cast and function call * multiplication and indirection + addition and unary plus ++ increment, prefix or postfix , comma - subtraction and unary minus -- decrement, prefix or postfix -> structure/union pointer (arrow) .
Expressions and Operators Operator Quick Reference Table 5-15 C Operators (Continued) Symbol Meaning >= greater-than-or-equal-to >> right shift ?: conditional [] subscript ^ OR (bitwise exclusive) | OR (bitwise inclusive) || OR (logical) ~ complement op= sizeof 138 assignment, compound compute object size at translation-time Chapter 5
Expressions and Operators Constant Expressions Constant Expressions Constant expressions contain only constant values. For example, the following are all constant expressions: • 5 • 5 + 6 * 13 / 3.
Expressions and Operators Integral Expressions Integral Expressions Integer expressions are expressions that, after all automatic and explicit type conversions, produce a result that has one of the integer types. If j and k are integers, the following are all integral expressions: • j • j * k • j / k + 3 • k - ‘a’ • 3 + (int) 5.
Expressions and Operators Floating-Point Expressions Floating-Point Expressions Floating-point expressions are expressions that, after all automatic and explicit type conversions, produce a result that has one of the floating-point types. If x is a float or double, the following are floating-point expressions: • x • x + 3 • x / y * 5 • 3.0 • 3.
Expressions and Operators lvalue Expressions lvalue Expressions An lvalue (pronounced “el-value”) is an expression that refers to a region of storage that can be manipulated. For example, all simple variables, like ints and floats are lvalues. An element of an array is also an lvalue; however an entire array is not. A member of a structure or union is an lvalue; an entire structure or union is not.
Expressions and Operators Pointer Expressions Pointer Expressions Pointer expressions are expressions that evaluate to an address value. These include expressions containing pointer variables, the address-of operator (&), string literals, and array names.
Expressions and Operators Evaluation of Expressions Evaluation of Expressions Expressions are evaluated at run time. The results of the evaluation are called by product values. For many expressions, you won't know or care what this byproduct is. In some expressions, though, you can exploit this feature to write more compact code. Examples The following expression is an assignment. x = 6; The value 6 is both the byproduct value and the value that gets assigned to x. The byproduct value is not used.
Expressions and Operators Evaluation of Expressions static char a_char, c[20] = {"Valerie"}, *pc = c; while (a_char = *pc++) { . . . This while statement uses C's ability to both assign and test a value. Every iteration of while assigns a new value to variable a_char. The byproduct of an assignment is equal to the value that gets assigned. The byproduct value will remain nonzero until the end of the string is reached.
Expressions and Operators Evaluation of Expressions 146 Chapter 5
6 Statements A program consists of a number of statements that are executed in sequence. A statement can be one of the following types: • Assignment, where values, usually the results of calculations, are stored in variables. • Input/Output, data is read in or printed out. • Control, the program makes a decision about what to do next. All statements end with a semicolon.
Statements Branch Statements Branch Statements Syntax goto label; goto *expression; continue; break; return [expression]; Description Branch statements transfer control unconditionally to another place in the executing program. The branch statements are goto, continue, break, and return.
Statements Branch Statements while (1) { if ((++i % 5) == 0) printf ("%2d ", i); if (i > 100) break; /* unconditional jump past the while loop } printf ("\n"); */ i = 0; while (1) { if ((++i % 5) == 0) printf ("%2d ", i); if (i > 100) { printf ("\n"); return; /* unconditional jump to calling function } } Chapter 6 */ 149
Statements Compound Statement or Block Compound Statement or Block Syntax compound-statement ::= {[declaration-list][statement-list]} declaration-list ::= declaration declaration-list declaration statement-list ::= statement statement-list statement Description A compound statement allows you to group statements together in a block of code and use them as if they were a single statement. Variables and constants declared in the block are local to the block and to any inner blocks unless declared extern.
Statements Expression and Null Statements Expression and Null Statements Syntax expression-statement ::= [expression]; Description C expressions can be statements. A null statement is simply a semicolon by itself. You can use any valid expression as an expression statement by terminating it with a semicolon. Expression statements are evaluated for their side effects; such as assignment or function calls.
Statements Labeled Statements Labeled Statements Syntax labeled-statement ::= identifier : statement case constant-expression : statement default: statement Description Labeled statements are those preceded by a name or tag. You can prefix any statement using a label so at some point you can reference it using goto statements. Any statement can have one or more labels. The case and default labels can only be used inside a switch statement. Example if (fatal_error) goto get_out; . . .
Statements Looping Statements Looping Statements Syntax while (expression) statement do statement while (expression); for ([expression1] ; [expression2]; [expression3]) statement Description Use looping statements to force a program to repeatedly execute a statement. The executed statement is called the loop body. Loops execute until the control is satisfied. The controlling expression may be any scalar data type. C has several looping statements: while, do…while, and for.
Statements Looping Statements for (i = 0; i < 5; i++) { a[i] = i; } 154 Chapter 6
Statements Selection Statements Selection Statements Syntax if (expression) statement [else statement] switch (expression) statement Description A selection statement alters a program's execution flow by selecting one path from a collection based on a specified controlling expression. The if statement and the switch statement are selection statements.
Statements break break Syntax break; Description A break statement terminates the execution of the most tightly enclosing switch statement or for, while, do…while loop. Control passes to the statement following the switch or iteration statement. You cannot use a break statement unless it is enclosed in a switch or loop statement. Further, a break only exits out of one level of switch or loop statement. To exit from more than one level, you must use a goto statement.
Statements continue continue Syntax continue; Description The continue statement halts execution of its enclosing for, while, or do/while loop and skips to the next iteration of the loop. In the while and do/while, this means the expression is tested immediately, and in the for loop, the third expression (if present) is evaluated. Example /* Program name is "continue_example". This program * reads a file of student names and test scores. It * averages each student's grade.
Statements continue if (i == 2) /* leave out this test score */ continue; tot_score += test_score; } /* end for i */ fscanf(fp, "\n"); /* read end-of-line at end of */ /* each student's data */ average = tot_score/4.0; printf("\nAverage test score: %4.1f\n", average); } /* end while */ fclose(fp); } If you execute this program, you get the following output: Student's name: Barry Quigley Grades: 85 91 88 100 75 Average test score: 87.
Statements do…while do…while Syntax do statement; while (expression); Arguments statement A null statement, simple statement, or compound statement. expression Any expression. Description The do statement executes statements within a loop until a specified condition is satisfied. This is one of the three looping constructions in C. Unlike the for and while loops, do…while performs statement first and then tests expression.
Statements do…while { int num, sum, square_sum; char answer; printf("\n"); do { printf("Enter an integer: "); scanf("%d", &num); sum = (num*(num+1))/2; square_sum = (num*(num+1)*(2*num+1))/6; printf("The summation of %d is: %d\n", num, sum); printf("The summation of its squares is: %d\n", square_sum); printf("\nAgain? "); fflush(stdin); scanf("%c", &answer); } while ((answer != 'n') && (answer != 'N')); } If you execute this program, you get the following output: Enter an integer: 10 The summation of 10 is:
Statements for for Syntax for ([expression1]; [expression2]; [expression3]) statement; Arguments expression1 This is the initialization expression that typically specifies the initial values of variables. It is evaluated only once before the first iteration of the loop. expression2 This is the controlling expression that determines whether or not to terminate the loop. It is evaluated before each iteration of the loop. If expression2 evaluates to a nonzero value, the loop body is executed.
Statements for 4. After statement is executed, expression3 is evaluated. Then the statement loops back to test expression2 again. for Loop Processing The for loop continues to execute until expression2 evaluates to 0 (false), or until a branch statement, such as a break or goto, interrupts loop execution. If the loop body executes a continue statement, control passes to expression3.
Statements for #define SIZE 10 int main(void) { int n, m, n_total, m_total, perm, i, j, mid, count; printf("Enter the numbers for the permutation (n things "); printf("taken m at a time)\nseparated by a space: "); scanf("%d %d", &n, &m); n_total = m_total = 1; for (i = n; i > 0; i--) /* compute n! */ n_total *= i; for (i = n - m; i > 0; i--) /* compute (n-m)! */ m_total *= i; perm = n_total/m_total; printf("P(%d,%d) = %d\n\n", n, m, perm); /* * * * * */ This series of for loops prints a pattern of "Z's" an
Statements for if (i < mid - j || i > mid + j) printf(" "); else printf("Z"); printf("\n"); } } } If you execute this program, you get the following output: Enter the numbers for the permutation (n things taken m at a time) separated by a space: 4 3 P(4,3) = 24 Now, print the pattern three times: Z ZZZ ZZZZZ ZZZZZZZ ZZZZZZZZZ ZZZZZZZZZZZ ZZZZZZZZZ ZZZZZZZ ZZZZZ ZZZ Z Z ZZZ ZZZZZ ZZZZZZZ ZZZZZZZZZ ZZZZZZZZZZZ ZZZZZZZZZ ZZZZZZZ ZZZZZ ZZZ Z Z ZZZ ZZZZZ ZZZZZZZ 164 Chapter 6
Statements for ZZZZZZZZZ ZZZZZZZZZZZ ZZZZZZZZZ ZZZZZZZ ZZZZZ ZZZ Z Chapter 6 165
Statements goto goto Syntax goto label; Arguments label This is a label or tag associated with an executable statement. Description The purpose of the goto statement is to enable program control to jump to some other statement. The destination statement is identified by a statement label, which is just a name followed by a colon. The label must be in the same function as the goto statement that references it. Few programming statements have produced as much debate as the goto statement.
Statements goto char answer; extern void something_different(void); circles: printf("Enter the circle's radius: "); scanf("%f", &radius); cir = 2 * PI * radius; area = PI * (radius * radius); printf("The circle's circumference is: %6.3f\n", cir); printf("Its area is: %6.
Statements goto Again? y or n: n Do you want to try something different? y Hello. This is something different.
Statements if if Syntax if (exp) /* format 1 */ statement if (exp) /* format 2 */ statement1 else statement2 Arguments exp Any expression. statement Any null statement, simple statement, or compound statement. A statement can itself be another if statement. Remember, a statement ends with a semicolon. Description The if statement tests one or more conditions and executes one or more statements according to the outcome of the tests.
Statements if else if (exp3) statement3 .. . else statement N The important thing to remember is that C executes at most only one statement in the if…else and if…else/if…else constructions. Several expressions may indeed be true, but only the statement associated with the first true expression is executed. Example 2 Expressions subsequent to the first true expression are not evaluated.
Statements if Braces also are important when you nest if statements. Since the else portion of the statement is optional, you may not have one for an inner if. However, C associates an else with the closest previous if statement unless you use braces to show that isn't what you want. For example: if (month == 12) { /* month = December */ if (day == 25) printf("Today is Christmas.\n"); } else printf("It's not even December.
Statements if printf("You have %d years before you're an adult.\n", of_age); } /* end else */ printf("\n"); printf("This part will help you decide whether to jog \ today.\n"); printf("What is the weather like?\n"); printf(" raining = r\n"); printf(" cold = c\n"); printf(" muggy = m\n"); printf(" hot = h\n"); printf(" nice = n\n"); printf("Enter one of the choices: "); fflush(stdin); scanf("\n%c", &answer); /* This if statement is an example of the third form (see * "Description" section.
Statements if hot = h nice = n Enter one of the choices: r It's too wet to jog today. Don't bother.
Statements return return Syntax return; return exp; /* first form */ /* second form */ Arguments exp Any valid C expression. Description The return statement causes a C program to exit from the function containing the return and go back to the calling block. It may or may not have an accompanying exp to evaluate. If there is no exp, the function returns an unpredictable value. A function may contain any number of return statements.
Statements return f2 = c; return c; /* OK, quietly converts c to float */ /* OK, quietly converts c to float */ } Pointer Return Types The C language is stricter about matching pointers. In the following example, f() is declared as a function returning a pointer to a char. Some legal and illegal return statements are shown.
Statements return Functions can return only a single value directly via the return statement. The return value can be any type except an array or function. This means that it is possible to return more than a single value indirectly by passing a pointer to an aggregate type. It is also possible to return a structure or union directly. HP C implements this by passing the structure or union by reference if the structure or union is greater than eight bytes. Example /* Program name is "return_example".
Statements return This program finds the length of any string you enter. Enter the string: Copenhagen The string is 10 characters. Again? y Enter the string: galaxy The string is 6 characters.
Statements switch switch Syntax switch ( exp ) { case const_exp : [statement]... [case const_exp : [statement]...] [default : [statement]...] } Arguments exp The integer expression that the switch statement evaluates and then compares to the values in all the cases. const_exp An integer expression to which exp is compared. If const_exp matches exp, the accompanying statement is executed. statement Zero or more simple statements.
Statements switch The following print_error() function, for example, prints an error message based on an error code passed to it. /* Prints error message based on error_code. * Function is declared with void because it doesn't * return anything. */ #include #define ERR_INPUT_VAL 1 #define ERR_OPERAND 2 #define ERR_OPERATOR 3 #define ERR_TYPE 4 void print_error(int error_code) { switch (error_code) { case ERR_INPUT_VAL: printf("Error: Illegal input value.
Statements switch Associating Statements with Multiple case Values Sometimes you want to associate a group of statements with more than one case value. To obtain this behavior, you can enter consecutive case labels. The following function, for instance, returns 1 if the argument is a punctuation character, or 0 if it is anything else. /* This function returns 1 if the argument is a * punctuation character. Otherwise, it returns 0. */ is_punc(char arg) { switch (arg) { case '.
Statements switch break; case 'B': case 'b': printf("Good\n"); break; case 'C': case 'c': printf("Average\n"); break; case 'D': case 'd': printf("Poor\n"); break; case 'E': case 'e': case 'F': case 'f': printf("Failure\n"); break; default: printf("Invalid grade\n"); break; } /* end switch */ printf("\nAgain? "); fflush(stdin); scanf("%s", &answer); } } If you execute this program, you get the following output: Enter student's grade: B Comments: Good Again? y Enter student's grade: C Comments: Average Again?
Statements while while Syntax while ( exp ) statement Arguments exp Any expression. statement This statement is executed when the while (exp) is true. Description The while statement executes the statements within a loop as long as the specified condition, exp, is true. This is one of the three looping constructions available in C. Like the for loop, the while statement tests exp and if it is true (nonzero), statement is executed. Once exp becomes false (0), execution of the loop stops.
Statements while while (*ptr_to_a_string++) count++; /* A simple statement loop */ printf("The string contains %d characters.\n", count); printf("The first word of the string is "); while (a_string[count2] != ' ' && a_string[count2] != '\0') { /* A compound statement loop */ printf ("%c", a_string[count2]); count2++; } printf("\n"); } If you execute this program, you get the following output: Enter a string Four score and seven years ago The string contains 30 characters.
Statements while 184 Chapter 6
7 Preprocessing Directives Preprocessing directives work as compiler control lines. They allow you to direct the compiler to perform certain actions on the source file. You can select from any of the following topics: • Source File Inclusion (#include) • Macro Replacement (#define, #undef) • Predefined Macros • Conditional Compilation (#if, #ifdef, ..
Preprocessing Directives Overview of the Preprocessor Overview of the Preprocessor A preprocessor is a text processing program that manipulates the text within your source file. You enter preprocessing directives into your source file to direct the preprocessor to perform certain actions on the source file.
Preprocessing Directives Overview of the Preprocessor Pragmas are implementation-dependent instructions that are directed to the compiler. Because they are very system dependent, they are not portable. All preprocessing directives begin with a pound sign (#) as the first character in a line of a source file. White space may precede the # character in preprocessing directives. The # character is followed by any number of spaces and horizontal tab characters and the preprocessing directive.
Preprocessing Directives Source File Inclusion (#include) Source File Inclusion (#include) You can include the contents of other files within the source file using the #include directive. Syntax include-directive ::= #include #include "filename" #include identifier Description In the third form above, identifier must be in the form of one of the first two choices after macro replacement.
Preprocessing Directives Source File Inclusion (#include) #else # define #endif filename "file2" #include filename Chapter 7 189
Preprocessing Directives Macro Replacement (#define, #undef) Macro Replacement (#define, #undef) You can define text substitutions in your source file with C macro definitions.
Preprocessing Directives Macro Replacement (#define, #undef) The formal parameters to the macro are separated with commas. They may or may not appear in the replacement list. When the macro is invoked, the actual arguments are placed in a parentheses-enclosed list following the macro name. Comma tokens enclosed in additional matching pairs of parentheses do not separate arguments but are themselves components of arguments.
Preprocessing Directives Macro Replacement (#define, #undef) In this example, the array x is dimensioned using the macro ARRAY_SIZE rather than the constant 1000. Note that expressions that may use the array can also use the macro instead of the actual constant: for (i=0; i
Preprocessing Directives Macro Replacement (#define, #undef) #define eatspace() while( (c=getc(input)) == ' ' || ); /* This macro skips white spaces Chapter 7 c == '\n' || c == '\t' */ 193
Preprocessing Directives Predefined Macros Predefined Macros In addition to __LINE__ and __FILE__ (see “Line Control (#line)” on page 198), ANSI C provides the __DATE__, __TIME__ and __STDC__ predefined macros. Table 7-1 describes the complete set of macros that are predefined to produce special information. They may not be undefined. Table 7-1 Macro Name Predefined Macros Description __DATE__ Produces the date of compilation in the form Mmm dd yyyy.
Preprocessing Directives Conditional Compilation (#if, #ifdef, ..#endif) Conditional Compilation (#if, #ifdef, ..#endif) Conditional compilation directives allow you to delimit portions of code that are compiled if a condition is true.
Preprocessing Directives Conditional Compilation (#if, #ifdef, ..#endif) The constant-expression is like other C integral constant expressions except that all arithmetic is carried out in long int precision. Also, the expressions cannot use the sizeof operator, a cast, or an enumeration constant. You can use the defined operator in the #if directive to use expressions that evaluate to 0 or 1 within a preprocessor line. This saves you from using nested preprocessing directives.
Preprocessing Directives Conditional Compilation (#if, #ifdef, ..#endif) Use the #else directive to specify an alternative section of code to be compiled if the #if, #ifdef, or #ifndef conditions fail. The code after the #else directive is compiled if the code following any of the if directives does not compile. The #elif constant-expression directive tests whether a condition of the previous #if, #ifdef, or #ifndef was false.
Preprocessing Directives Line Control (#line) Line Control (#line) You can cause the compiler to increment line numbers during compilation from a number specified in a line control directive. (The resulting line numbers appear in error message references, but do not alter the line numbers of the actual source code.
Preprocessing Directives Pragma Directive (#pragma) Pragma Directive (#pragma) You can provide instructions to the compiler through inclusion of pragmas. Syntax pragma-directive ::= #pragma replacement-list Description The #pragma preprocessing directive provides implementation-dependent information to the compiler. See Chapter 9, “Compiling and Running HP C Programs,” on page 207 for descriptions of pragmas recognized by HP C/HP-UX. Any pragma that is not recognized by the compiler is ignored.
Preprocessing Directives _Pragma _Pragma _Pragma is a preprocessing unary operator. Syntax _Pragma (string-literal) _Pragma is a new preprocessing operator and is a part of C99 standards. The string literal is destringized by deleting the L prefix, if present. _Pragma deletes the leading and trailing double quotes, replacing each escape sequence by a double-quote, and replacing the escape sequence by a single backlash.
Preprocessing Directives _Pragma expands to #pragma ALIGN 4 Example 7-3 _Pragma Operator Usage #define FOO "ALIGN 4" _Pragma(FOO) expands to #pragma ALIGN 4 Chapter 7 201
Preprocessing Directives Error Directive (#error) Error Directive (#error) Syntax #error [pp-tokens] The #error directive causes a diagnostic message, along with any included token arguments, to be produced by the compiler.
Preprocessing Directives Trigraph Sequences Trigraph Sequences The C source code character set is a superset of the ISO 646-1983 Invariant Code Set. To enable programs to be represented in the reduced set, trigraph sequences are defined to represent those characters not in the reduced set. A trigraph is a three character sequence that is replaced by a corresponding single character. Table 7-2 gives the complete list of trigraph sequences and their replacement characters.
Preprocessing Directives Trigraph Sequences 204 Chapter 7
8 C Library Functions The C library (/usr/lib/hpux32/libc.so or /usr/lib/hpux64/libc.so) is divided into different subsections. Each subsection has a header file that defines the objects found in that section of the library. The standard headers are: The order of inclusion of these header files using the #include directive makes no difference.
C Library Functions { . . . f(add1);
9 Compiling and Running HP C Programs This chapter describes how to compile and run HP C programs. The compiler command and its options are presented. You can compile HP C programs to produce assembly, object, or executable files. You can also optionally optimize code to improve application run-time speed.
Compiling and Running HP C Programs Compiling HP C Programs Compiling HP C Programs When you compile a program, it passes through one or more of the following steps depending upon which command line options you use: • Preprocessor: This phase examines all lines beginning with a # and performs the corresponding actions and macro replacements. • Compilation Process: This phase takes the output of the preprocessor and generates object code.
Compiling and Running HP C Programs Compiling HP C Programs Files with names ending in .i are assumed to be preprocessor output files. Files ending in .i are processed the same as .c files, except that the preprocessor is not run on the .i file before the file is compiled. Files with names ending in .s are assumed to be assembly source files; the compiler invokes the assembler to produce .o files from these. Files with .
Compiling and Running HP C Programs Compiling HP C Programs cc my_file.c -v -g -DPROG=sub cc my_file.c -vg -D PROG=sub cc my_file.c -vgDPROG=sub cc -vgDPROG=sub my_file.c HP C Compiler Options Table 9-1 summarizes the command line options supported by HP Integrity servers. Some of these options are HP aC++ options. Refer to HP aC++/HP C Programmer’s Guide for detailed information on compiler options. Table 9-1 HP C Compiler Options at a Glance Option Description -.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description -Bextern Performs the same operation as +Oextern=sym1,sym2,sym3... except that symbols are loaded from an existing file, instead of specified on the command line. -Bprotected Assigns protected export class to symbols. -Bprotected_data Assigns protected export class to data symbols. -Bprotected_def Assigns protected export class to locally defined symbols.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description -[no]fpwidetypes Enables [disables] extended and quad floating point data types. -g Inserts information for the symbolic debugger in the object file. -g0 Causes the compiler to generate complete debug information for the debugger. -g1 Causes the debugger to generate minimal information for the debugger.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description -p Inserts information required by the prof profiler in the object file. -P Performs preprocessing only with output to the corresponding .i file. -q Marks the executable as demand loadable. -Q Marks the executable as not being demand loadable. -r Retains relocation information in the output file for subsequent relinking.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description +cond_rodata Allows more data to be placed in a read-only section. +d Prevents expansion of inline functions. +DD32 Generates ILP32 code and is the default. +DD64 Generates LP64 code. +DSmodel Performs instruction scheduling for a specific implementation of Itanium-based architecture. +DOosname Sets the target operating system for the compiler.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description +inst_directed Indicates to the compiler that no templates are to be instantiated (except explicit instantiations). +inst_implicit_include Specifies that the compiler use a process similar to the cfront source rule for locating template definition files. +inst_include_suffixes Specifies the file name extensions that the compiler uses to locate definition files.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description +o Prints hexadecimal code offsets in the source code listing. +O[no]cross_region_addressing Enables [disables] the use of cross-region addressing. +O[no]cxlimitedrange Enables [disables] the use of the usual formulas for complex arithmetic.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description +O[no]loop_transform Transforms [does not transform] eligible loops for improved cache and performance. +O[no]loop_unroll Enables [disables] loop unrolling. +O[no]loop_unroll_jam Enables [disables] loop unrolling and jamming. +O[no]openmp Honors [silently ignores] OpenMP directives.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description +O[no]store_ordering Preserves [does not preserve] the original program order for stores to memory that is visible to multiple threads. +O[no]volatile Treats all global variables as [not] volatile. +O[no]whole_program_mode Enables [disables] assertion for files compiled with this option. +O[0|1|2|3|4] Specifies the level of optimization.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description +Oshortdata Places objects in the short data area; and references to such data assume it resides in the short data area +Otype_safety Controls type-based aliasing assumptions. +Ounroll_factor Applies the unroll factor to all loops in the current translation unit. +Oprofile=collect Prepares the object code for profile-based optimization data collection.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-1 HP C Compiler Options at a Glance (Continued) Option Description +uc Makes unqualified char data types unsigned. +w Warns about all questionable constructs and gives pedantic warnings. +W arg1[,arg2,...argn] Suppresses the specified warnings. +We n1[,n2,...nN] Changes the specified warnings to errors. +wn Specifies the level of warning messages. Warns about all questionable constructs and gives pedantic warnings. +Ww n1[,n2,.
Compiling and Running HP C Programs Compiling HP C Programs • cc prog.c -co /users/my/prog.o compiles the source file prog.c and places the object file prog.o in /users/my/prog.o. • cc -Wp,-H150000 p1.c p2.c p3.c -o p +legacy_cpp compiles the source files in the option -H150000 to the preprocessor cpp to increase the define table size from the default. • cc -Wl,-vt *.c -o vmh compiles all files in the working directory ending with .
Compiling and Running HP C Programs Compiling HP C Programs • cc +DD64 +Z -c prog.c compiles prog.c for use in a large shared library or executable in 64-bit mode. • cc +DD32 +z -c prog.c compiles prog.c in 32-bit mode for use in a shared library with less than 16K of symbols. • cc +DD64 prog.c compiles prog.c in 64-bit mode. Refer to the discussion on optimization options in the C online help or the HP C/HP-UX Programmer’s Guide for more information.
Compiling and Running HP C Programs Compiling HP C Programs For example, the following in C shell notation setenv CCOPTS -v cc -g prog.c is equivalent to cc -v -g prog.c For example, the following in C shell notation setenv CCOPTS "-v | +O1" cc +O2 prog.c is equivalent to cc -v +O2 prog.c +O1 In the above example, level 1 optimization is performed, since the +O1 argument appearing after the vertical bar in CCOPTS takes precedence over the cc command line arguments.
Compiling and Running HP C Programs Compiling HP C Programs directory is the name of an HP-UX directory where you want HP C to put temporary files during compilation. aCC_MAXERR Environment Variable This release of HP C compiler provides support to specify the maximum number of errors emitted before the compilation aborts. In the earlier versions, the compiler stopped, if it recognized more than 99 errors while compiling.
Compiling and Running HP C Programs Compiling HP C Programs Table 9-2 Native and Alternate Toolset Location (Continued) Native Location Alternate Toolset Location /opt/ansic/lbin/ecom (for A.06.*) /opt/xdk-ia/opt/ansic/lbin/ecom (for A.06.*) /opt/ansic/lbin/ctcom (for A.05.*) /opt/xdk-ia/opt/ansic/lbin/ctcom (for A.05.*) /opt/langtools/lbin/cpp.ansi /opt/xdk-ia/opt/langtools/lbin/cpp.
Compiling and Running HP C Programs Pragmas Pragmas A #pragma directive is an instruction to the compiler. Put pragmas in your C source code where you want them to take effect, but do not use them within a function. A pragma has effect from the point at which it is included to the end of the translation unit (or until another pragma changes its status).
Compiling and Running HP C Programs Pragmas FINI Pragma #pragma FINI “string” Use the compiler pragma FINI to specify a termination function. The function specified by the FINI pragma is called after the C program terminates by either calling the libc exit() function, returning from the main or _start functions, or when the shared library which contains the FINI is unloaded from memory. Like the function called by the INIT pragma, the termination function takes no arguments and returns nothing.
Compiling and Running HP C Programs Pragmas For example, the following command builds the name $CODE&MINE$: #pragma locality “mine” Code that is not headed by a LOCALITY pragma is associated with the name $CODE$. An empty "string" causes the code name to revert to the default name of $CODE$. VERSIONID Pragma #pragma VERSIONID "string" Specifies a version string to be associated with a particular piece of code. The string is placed into the object file produced when the code is compiled.
Compiling and Running HP C Programs Pragmas The PACK pragma is not intended to be an “extension” of the HP_ALIGN pragma. It is, instead, a simple and highly portable way of controlling the alignment of aggregates. It has some significant differences with the HP_ALIGN pragma, including uniform bitfield alignment, uniform struct and union alignment, and the lack of PUSH and POP functionality.
Compiling and Running HP C Programs Pragmas NOTE 230 The HP_ALIGN pragma, which is supported by HP ANSI C compiler, is not supported by HP aC++. The pack and unalign pragmas can replace most of the HP_ALIGN functionality.
Compiling and Running HP C Programs Pragmas Optimization Pragmas For additional information on the following optimization pragmas refer to HP aC++/HP C Programmer's Guide. FLOAT_TRAPS_ON Pragma #pragma FLOAT_TRAPS_ON { functionname,...functionname } #pragma FLOAT_TRAPS_ON {_ALL } The FLOAT_TRAPS_ON pragma informs the compiler that you may have enabled floating-point trap handling.
Compiling and Running HP C Programs Pragmas FastCall Pragmas The compiler directives described in this section are designed to speed up shared library calls. HP_DEFINED_EXTERNAL Pragma #pragma HP_DEFINED_EXTERNAL sym1, sym2, ... The externally defined symbol pragma specifies that the designated symbols are imported from another load module (program file or shared library). Note that this pragma currently works in 32-bit mode only. For 64-bit mode, use the option +Oextern.
Compiling and Running HP C Programs Pragmas Example: The function below prefetches ia and b, but not a[ia[i]] when compiled with +O2 +Odataprefetch +DA2.0 (or +DA2.0W).
Compiling and Running HP C Programs Running HP C Programs Running HP C Programs After a program is successfully linked, it is in executable form. To run the program, enter the executable filename (either a.out or the name following the -o option).
10 HP C/HP-UX Implementation Topics This chapter describes the following topics that are specific to programming in C on HP-UX systems: • “Data Types” on page 236 • “Bit-Fields” on page 239 • “IEEE Floating-Point Format” on page 240 • “Lexical Elements” on page 242 • “Structures and Unions” on page 243 • “Type Mismatches in External Names” on page 244 • “Expressions” on page 245 • “Pointers” on page 246 • “Maximum Number of Dimensions of an Array” on page 247 • “Scope of extern Declaratio
HP C/HP-UX Implementation Topics Data Types Data Types Data types are implemented in HP C/HP-UX as follows: • The char type is signed. • All types can have the register storage class, although it is only honored for scalar types. Ten register declarations per function are honored. • The signed integer types are represented internally using twos complement form. • Structures and unions start and end on an alignment boundary which is that of their most restrictive member.
HP C/HP-UX Implementation Topics Data Types Table 10-1 Type HP C/HP-UX Data Types (Continued) Bits Bytes Low Bound High Bound Comments long (ILP32) 32 4 -2,147,483,6 48 2,147,483,64 7 Signed integer long (LP64) 64 8 -263 263 -1 Signed integer long long 64 8 -263 263 -1 Signed integer unsigned long (ILP32) 32 4 0 4,294,967,29 5 Unsigned integer unsigned long (LP64) 64 8 0 264 -1 Unsigned integer unsigned long long 64 8 0 264 -1 Unsigned integer float 32 4 See (a
HP C/HP-UX Implementation Topics Data Types b. 3.40282347E+38F c. Least normalized: 2.2250738585072014E-308 Least denormalized: 4.9406564584124654E-324 d. 1.7976931348623157E+308 e. Least normalized: 3.3621031431120935062626778173217526026E-4932L Least denormalized: 6.4751751194380251109244389582276465525E-4966L e. 1.
HP C/HP-UX Implementation Topics Bit-Fields Bit-Fields • Bit-fields in structures are packed from left to right (high-order to low-order). • The high order bit position of a “plain” integer bit-field is treated as a sign bit. • Bit-fields of types char, short, long, long long, and enum are allowed. • The maximum size of a bit-field is 64 bits. • If a bit-field is too large to fit in the current word, it is moved to the next word.
HP C/HP-UX Implementation Topics IEEE Floating-Point Format IEEE Floating-Point Format The internal representation of floating-point numbers conforms to the IEEE floating-point standard, ANSI/IEEE 754-1985, as shown in Figure 10-1. Figure 10-1 Internal Representation of Floating-Point Numbers Float bits Double bits Long Double bits s exp mantissa 1 8 23 s exp mantissa 1 11 52 s exp mantissa 1 15 112 The s field contains the sign of the number.
HP C/HP-UX Implementation Topics IEEE Floating-Point Format NaNs are binary floating-point numbers that have all ones in the exponent and a nonzero fraction. NaN is a term used for a binary floating-point number that has no value (that is, “Not A Number”). If E is within the range Emin <= E <= Emax the mantissa field contains the number in a normalized form, preceded by an implicit 1 and binary point.
HP C/HP-UX Implementation Topics Lexical Elements Lexical Elements • Identifiers: 255 characters are significant in internal and external names. • Character Constants: Any character constant of more than one character produces a warning. The value of an integral character constant containing more than one character is computed by concatenating the 8-bit ASCII code values of the characters, with the leftmost character being the most significant.
HP C/HP-UX Implementation Topics Structures and Unions Structures and Unions Structure or union references that are not fully qualified (see example below) are flagged with an error by the compiler. struct{ int j; struct {int i;}in; } out; out.i=3; The correct statement for the example above is out.in.i = 3;.
HP C/HP-UX Implementation Topics Type Mismatches in External Names Type Mismatches in External Names It is illegal to declare two externally visible identifiers of different types with the same name in separately compiled translation units. The linker might not diagnose such a mismatch.
HP C/HP-UX Implementation Topics Expressions Expressions The value of an expression that overflows or underflows is undefined, except when the operands are unsigned.
HP C/HP-UX Implementation Topics Pointers Pointers • Pointers to functions should not be compared using relational operators because the pointers represent external function labels and not actual addresses. • Dereferencing a pointer that contains an invalid value results in a trap if the address references protected memory or if the address is not properly aligned for the object being referenced.
HP C/HP-UX Implementation Topics Maximum Number of Dimensions of an Array Maximum Number of Dimensions of an Array Arrays can have up to 252 dimensions.
HP C/HP-UX Implementation Topics Scope of extern Declarations Scope of extern Declarations Identifiers for objects and functions declared within a block and with the storage class extern have the same linkage as any visible declaration with file scope. If there is no visible declaration with file scope, the identifier has external linkage, and the definition remains visible until the end of the translation unit.
HP C/HP-UX Implementation Topics Conversions Between Floats, Doubles, and Long Doubles Conversions Between Floats, Doubles, and Long Doubles • When a long double is converted to a double or float, or when a double is converted to a float, the original value is rounded to the nearest representable value as the new type. If the original value is equally close to two distinct representable values, then the value chosen is the one with the least significant bit equal to zero.
HP C/HP-UX Implementation Topics Statements Statements • The types of switch expressions and their associated case label constants do not need to match. Integral types can be mixed. • All expressions of integral types are allowed in switch statements.
HP C/HP-UX Implementation Topics Preprocessor Preprocessor • The maximum nesting depth of #include files is 35. • For include files that are enclosed in double quotes and do not begin with a /, the preprocessor will first search the current directory, then the directory named in the -I option, and finally, in the standard include directory /usr/include.
HP C/HP-UX Implementation Topics Library Functions and Header Files Library Functions and Header Files This section describes the implementation of library functions in HP C/HP-UX. For complete information about library functions on HP C/HP-UX, see the HP-UX Reference manual and HP-UX Linker and Libraries Online User Guide. The Math Library When using any of the mathematical functions in the header, you must include the -lm flag on the cc or ld command when linking.
HP C/HP-UX Implementation Topics The varargs Macros The varargs Macros The varargs macros allow accessing arguments of functions where the number and types of the arguments can vary from call to call. NOTE The header has been superseded by the standard header , which provides all the functionality of the varargs macros. The header is retained for compatibility with pre-ANSI compilers and earlier releases of HP C/HP-UX.
HP C/HP-UX Implementation Topics The varargs Macros enum arglisttype a2; enum argtype ptype; int i, *p; char c; double d; /* Initialize the varargs mechanism */ va_start(ap); /* Get the first argument, and arg list flag */ a1 = va_arg (ap, int); a2 = va_arg (ap, enum arglisttype); printf ("arg count = %d\n", a1); if (a2 == VAR_LIST_PRESENT) { /* pick up all the arguments */ do { /* get the type of the argument */ ptype = va_arg (ap, enum argtype); /* retrieve the argument based on the type */ switch (ptype)
HP C/HP-UX Implementation Topics The varargs Macros default: printf ("bad argument type %d\n", ptype); ptype = END_OF_LIST; /* to break loop */ break; } /* switch */ } while (ptype != END_OF_LIST); } /* Clean up */ va_end (ap); } main() { int x = 99; foo (1, NO_VAR_LIST); foo (2, VAR_LIST_PRESENT, DOUB, 3.0, PINT, &x, END_OF_LIST); } C9X standard macros The C9X standard-compliant version of "variadic" or variable argument (varargs) macro notation has been added to the HP ANSI C compiler.
HP C/HP-UX Implementation Topics The varargs Macros In the use of a variable arguments macro, a one-to-one correspondence is set up between the arguments in use and those in its definition. This is up to, but not including, the variable argument parameter. The rest of the arguments in the use of the macro definition are referred to as the trailing arguments.
HP C/HP-UX Implementation Topics The varargs Macros printf(f, s) How HP C implements GNU and C9X macros If you intend to use GNU style variable argument macros in HP C, note that you can make the concatenation operator ## prevent syntax errors from occurring when the variable argument comes in as empty (the null string). However, you can also insert whitespace to the left of the left operand of ## to more accurately specify the intended left operand. For example, if you use #define foo(f, s...
HP C/HP-UX Implementation Topics The varargs Macros printf(f, Because there is no parameter by that name for foo, it is erased.
HP C/HP-UX Implementation Topics HP Specific Type Qualifiers HP Specific Type Qualifiers See “HP-Specific Type Qualifiers” on page 44.
HP C/HP-UX Implementation Topics Location of Files Location of Files Table 10-5 lists the location of the HP C files. Table 10-5 Location of Files File or Library Location Driver /opt/ansic/bin/cc /opt/ansic/bin/c89 Preprocessor /opt/langtools/lbin/cpp (Compatibility mode) /opt/langtools/lbin/cpp.ansi (ANSI mode) (Only used with +legacy_cpp) Compiler /opt/ansic/lbin/ecom (for A.06.*) /opt/ansic/lbin/ctcom (for A.05.
HP C/HP-UX Implementation Topics Location of Files Table 10-5 Location of Files (Continued) File or Library Manpages Location • Manpages in English /opt/ansic/share/man/man1.Z/cc.1 /opt/ansic/share/man/man1.Z/c89.1 /opt/ansic/share/man/man1.Z/c99.1 /opt/langtools/share/man/man1.Z/cpp.1 /opt/langtools/share/man/man1.Z/lex.1 /opt/langtools/share/man/man1.Z/yacc.1 • Manpages in Japanese /opt/ansic/share/man/ja_JP.SJIS/man1.Z/cc.1 /opt/ansic/share/man/ja_JP.SJIS/man1.Z/c89.1 /opt/ansic/share/man/ja_JP.
HP C/HP-UX Implementation Topics Location of Files Table 10-5 Location of Files (Continued) File or Library Location Online Help /opt/ansic/html/C/guide C Tools /opt/langtools/bin /opt/langtools/lbin *You can change the default location for the temporary files used and created by the C compiler by setting the environment variable TMPDIR. If the compiler cannot write to $TMPDIR, it uses the default location /var/tmp. See the HP-UX Reference for details.
A Syntax Summary This appendix presents a summary of the C language syntax using a variation of the Backus Naur syntax.
Syntax Summary Lexical Grammar Lexical Grammar Tokens token ::= keyword identifier constant string-literal operator punctuator preprocessing-token ::= header-name identifier pp-number character-constant string-literal operator punctuator each non-white-space character cannot be one of the above Keywords keyword ::= any word from the set: auto extern sizeof break float static case for struct char goto switch const if __thread (HP-UX 10.
Syntax Summary Lexical Grammar Identifiers identifier ::= nondigit identifier nondigit identifier digit identifier dollar-sign nondigit ::= _ q H Y any a b r s I J Z character c d e f g t u v w x K L M N O from the set: h i j k l m n o p y z A B C D E F G P Q R S T U V W X digit ::= any character from the set: 0 1 2 3 4 5 6 7 8 9 dollar-sign ::= the $ character Constants constant ::= floating-constant integer-constant enumeration-constant character-constant floating-constant ::= fractional-constant [e
Syntax Summary Lexical Grammar digit-sequence ::= digit digit-sequence digit floating-suffix ::= f l F L integer-constant ::= decimal-constant [integer-suffix] octal-constant [integer-suffix] hexadecimal-constant [integer-suffix] decimal-constant ::= nonzero-digit decimal-constant digit octal-constant ::= 0 octal-constant octal-digit hexadecimal-constant ::= 0x hexadecimal-digit 0X hexadecimal-digit hexadecimal-constant hexadecimal-digit nonzero-digit ::= any character from the set: 1 2 3 4 5 6 7 8 9 octal
Syntax Summary Lexical Grammar unsigned-suffix ::= u U length-suffix ::= long-suffix long-long-suffix long-suffix ::= any character from the set l L long-long-suffix ::= any character from the set ll LL Ll lL enumeration-constant ::= identifier character-constant ::= 'c-char-sequence' L'c-char-sequence' c-char-sequence ::= c-char c-char-sequence c-char c-char ::= any character in the source character set except the single quote ('), backslash (\), or new-line character escape-sequence escape-sequence ::= s
Syntax Summary Lexical Grammar hexadecimal-escape-sequence ::= \x hexadecimal-digit hexadecimal-escape-sequence hexadecimal-digit 268 Appendix A
Syntax Summary Lexical Grammar String Literals string-literal ::= "[s-char-sequence]" L"[s-char-sequence]" s-char-sequence ::= s-char s-char-sequence s-char s-char ::= any character in the source character set except the double-quote (") , backslash (\), or new-line character escape-sequence Operators operator [ ++ / && = , ::= One selected from: ] ( ) . -> -& * + % << >> < > || ? : *= /= %= += -= # ## ~ <= <<= ! sizeof >= == >>= &= != ^ ^= |= ...
Syntax Summary Lexical Grammar the newline character and > q-char-sequence ::= q-char q-char-sequence q-char q-char ::= any character in the source character set except the newline character and " Preprocessing Numbers pp-number ::= digit . digit pp-number pp-number pp-number pp-number pp-number 270 digit nondigit e sign E sign .
Syntax Summary Phrase Structure Grammar Phrase Structure Grammar Expressions primary-expression ::= identifier constant string-literal ( expression ) postfix-expression ::= primary-expression postfix-expression postfix-expression postfix-expression postfix-expression postfix-expression postfix-expression [ expression ] ( [argument-expression-list] ) .
Syntax Summary Phrase Structure Grammar cast-expression multiplicative-expression * cast-expression multiplicative-expression / cast-expression multiplicative-expression %% cast-expression additive-expression ::= multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression shift-expression ::= additive-expression shift-expression << additive-expression shift-expression >> additive-expression relational-expression ::= shift-expression relational-e
Syntax Summary Phrase Structure Grammar logical-AND-expression && inclusive-OR-expression logical-OR-expression ::= logical-AND-expression logical-OR-expression || logical-AND-expression conditional-expression ::= logical-OR-expression logical-OR-expression ? logical-OR-expression : conditional-expression assignment-expression ::= conditional-expression unary-expression assign-operator assignment-expression assign-operator = *= ::= one selected from the set /= %= += -= <<= >>= &= ^= |= expression ::=
Syntax Summary Phrase Structure Grammar declarator = initializer storage-class-specifier ::= typedef extern static auto register type-specifier ::= void char short int long float double signed unsigned struct-or-union-specifier enum-specifier typedef-name struct-or-union specifier ::= struct-or-union [identifier] {struct-declaration-list} struct-or-union identifier struct-or-union ::= struct union struct-declaration-list ::= struct-declaration struct-declaration-list struct-declaration struct-declaration :
Syntax Summary Phrase Structure Grammar struct-declarator-list ::= struct-declarator struct-declarator-list , struct-declarator struct-declarator ::= declarator [declarator] : constant-expression enum-specifier ::= [ type-specifier ] enum [identifier] {enumerator-list} [ type-specifier ] enum identifier enumerator-list ::= enumerator enumerator-list , enumerator enumerator ::= enumeration-constant enumeration-constant = constant-expression type-qualifier ::= const noalias volatile declarator ::= [pointer]
Syntax Summary Phrase Structure Grammar parameter-type-list ::= parameter-list parameter-list , ...
Syntax Summary Phrase Structure Grammar Statements statement := labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement labeled-statement := identifier : statement case constant-expression : statement default: statement compound-statement := { [declaration-list] [statement-list] } declaration-list := declaration declaration-list declaration statement-list := statement statement-list statement expression-statement := [expression]; selection-statement
Syntax Summary Phrase Structure Grammar continue ; break ; return [expression] ; External Definitions translation-unit := external-declaration translation-unit external-declaration external-declaration := function-definition declaration function-definition := [declaration-specifiers] declarator [declaration-list] compound-statement 278 Appendix A
Syntax Summary Preprocessing Directives Preprocessing Directives preprocessing-file := [group] group := group-part group group-part group-part := [pp-tokens] new-line if-section control-line if-section := if-group [elif-groups] [else-group] endif-line if-group := # if constant-expression new-line [group] # ifdef identifier new-line [group] # ifndef identifier new-line [group] elif-groups := elif-group elif-groups elif-group elif-group := # elif constant-expression new-line [group] else-group := # else new-
Syntax Summary Preprocessing Directives # line # error # pragma # pp-tokens new-line [pp-tokens] new-line [pp-tokens] new-line new-line replacement-list := [pp-tokens] pp-tokens := preprocessing-token pp-tokens preprocessing-token new-line := the new-line character 280 Appendix A
Index Symbols !, logical NOT operator, 113 #elif, 195 #else, 195 #endif, 195 #error, 202 #if, 195 #ifdef, 195 #ifndef, 195 #line, 198 #pragma, 199 %, modulo division operator, 84 %=, assignment operator, 87 &&, logical AND operator, 113 &, address of operator, 118 *, dereferencing operator, 118 *, multiplication operator, 84 *=, assignment operator, 87 ++,increment operator, 109 +, addition operator, 84 +, unary plus operator, 84 +=, assignment operator, 87 , comma operator, 103 -, subtraction operator, 84
Index char type, 40 character constants, 27 comma operator (,), 103 comments in a source file, 9 compilation ANSI mode, 2 compatibility mode, 3 compilation process, 208 conditional, 186, 195 compiler options summary, 210 compiling HP C programs, 208 compound literal, 67 compound statement, 150 conditional compilation, 186, 195 conditional operator (? ), 104 const keyword, 13 constant expressions, 139 constants, 24 integer, 24 continuation lines, 8 continue statement, 148, 157 conversions arithmetic, 80 floa
Index function, 81, 253 call, 106 declarator, 58 definitions, 70 inline, 73 library, 205 prototypes, 70 referencing functions instead of macros, 205 function calls by reference, 107 by value, 107 int type, 40 integer constants, 24 integers expressions, 140 integral conversions, 80 promotion, 76 unsigned preserving rules, 76 G Gather/Scatter prefetch pragma, 232 GNU standards, 255 goto statement, 148, 152, 166 K keywords, 11 H header files location, 205 specifying, 205 help, online, 5 hexadecimal constan
Index N name spaces, 21 names type, 60 newline characters, 8 , 231 pragmas , 231 NO_SIDE_EFFECTS pragma, 231 NOINLINE pragma, 231 no-operation statements, 151 -notrigraph option, 203 null statement, 151 O octal constants, 24 online help, 5 operator, 83 arithmetic, 84 assignment, 87 bit, 93 cast, 98 comma (,), 103 conditional (?:), 104 decrement, 109 defined, 195 increment, 109 logical, 113 precedence, 135 sizeof, 131 optimization, 208 OPTIMIZE pragma, 231 overflow expression, 245 P PACK pragma, 228 poin
Index return statement, 148, 174 row-major array storage, 56 running HP C programs, 234 S scalar objects initializing, 63 scope, 247 SDK/XDK support, 224 SDKROOT environment variable, 224 selection statements, 155 self-referential structure, 50 shared libraries, 208 short keyword, 15 short type, 40 signed keyword, 15 simple assignment, 87 sized enum, 53 sizeof operator, 60, 131 sizes of data types, 236 source files assembly, 208 HP C, 208 inclusion, 188 parts of C program, 8 specifier storage-class, 38 stru
Index va_start macro, 253 value preserving rules, 76 variable length array declarator, 57 variables syntax for declaring, 18 VERSIONID pragma, 228 void type, 40 volatile type qualifier, 18, 45 W wchar_t typedef, 65 while statement, 182 white space, 8 wide char constant, 28 286