- A bit-field or field for short, is a set of adjacent bits within a single implementation-defined storage unit that we will call a "word"
Friday, June 17, 2011
6.9 Bit-fields
6.8 Unions
- A union is a variable that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements
- Unions provide a way to manipulate different kinds of data in a single area of storage, without embedding any machine-dependent information in the program
- Syntax:
Thursday, June 16, 2011
6.7 Typedef
- C provides a facility called typedef for creating new data type names
- ie. typedef int Length; (Length a synonym for int)
- ie. typedef char *String; (String a synonym for char * or character pointer)
Wednesday, June 15, 2011
Tuesday, June 14, 2011
6.3 Arrays of Structures
- Structure type key, with an array keytab of structures. Each elements of the array is a structure:
- Initialization:
Monday, June 13, 2011
6.2 Structures and Functions
- The only legal operations on a structure are copying it or assigning to it as a unit, taking its address with & and accessing its member
- Copy and assignment including passing arguments to functions and returning values from function as well
- Structure may not be compared
- A structure may be initialized by a list of constant member values; an automatic structure may also be initialized by an assignment
Thursday, June 9, 2011
6.1 Basics of Structures
- Structure example:
- An optional name called a structure tag may follow the word struct. (ie point)
- The variables named in a structure are called members
- A struct declaration defines a type
- A struct declaration that is not followed by a list of variables reserves no storage, it merely describes a template or the shape of a structure.
- If the declaration is tagged, however, the tag can be used later in definitions of instances of the structure
- ie: struct point pt; defines a variable pt which is a structure of type struct point
- A member of a particular structure is referred to in an expression by a construction of the form: structure-name.member (ie. point.x )
- Structures can be nested:
Wednesday, June 8, 2011
Chapter 6 Structures
- A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling
- Structures help to organize complicated data, particularly in large programs, because they permit a group of related variables to be treated as a unit instead of as separate entities
- ANSI standard: Structures may be copied and assigned to, passed to functions, and returned by functions.
Tuesday, June 7, 2011
5.12 Complicated Declarations
- C is sometimes castigated for the syntax of its declarations, particularly ones that involve pointers to functions
- The syntax is an attempt to make the declaration and the use agree; it works well for simple cases, but it can be confusing for the harder ones, because declarations cannot be read from left to right, and because parentheses are over-used.
- Problem:
- * is a prefix operator and it has lower precedence than ( ), so parentheses are necessary to enforce proper association
Monday, June 6, 2011
5.11 Pointers to Functions
- In C, a function itself is not a variable, but it is possible to define pointers to functions, which can be assigned, placed in arrays, passed to functions, returned by functions, and so on
Friday, June 3, 2011
5.10 Command-Line Arguments
- In environments that support C, there is a way to pass command-line arguments or parameters to a program when it begins executing.
- When main is called, it is called with two arguments or parameters.
- The first (conventionally called argc, for argument count) is the number of command-line arguments the program was invoked with; the second (argv for argument vector) is a pointer to an array of character strings that contain the arguments, one per string.
- The simplest illustration is the program echo, which echoes its command-line arguments on a single line, separated by blanks:
- By convention, argv[0] is the name by which the program was invoked, so argc is at least 1
- If argc is 1, there are no command-line arguments after the program name
- In the example above, argc is 3; argv[0] is "echo", argv[1] is "hello," and argv[2] is "world"
- Standard requires that argv[argc] be a null pointer:
- First version of echo treats argv as an array of character pointers. Since argv is a pointer to an array of pointers, we can manipulate the pointer rather than index the array:
- Second version is based on incrementing argv, which is a pointer to pointer to char, while argc is counted down:
Thursday, June 2, 2011
5.9 Pointers vs Multi-dimensional Arrays
- Compare the declaration and picture for an array of pointers:
- Important advantage of the pointer arrays is that the rows of the array may be of different lengths
Wednesday, June 1, 2011
Thursday, May 26, 2011
5.7 Multi-dimensional Arrays
- C provides rectangular multi-dimensional arrays, in practice they are much less used than array of pointers
- In C, a two dimensional array is really a one dimensional array, each of whose elements is an array. Hence subscripts are written as:
- An array is initialized by a list of initializers in braces
- If a two-dimensional array is to be passed to a function, the parameter declaration in the function must include the number of columns; the number of rows is irrelevant
Wednesday, May 25, 2011
5.6 Pointer Arrays; Pointers to Pointers
- Pointers are variables and can be stored in arrays
- Sort a set of text lines in alphabet order:
- Each line of character array can be accessed by a pointer to its first character and pointers themselves can be stored in an array
- When two out-of-order lines have to be exchanged, the pointers in the pointer array are exchanged, not the text lines themselves
- These prevent complicated storage management and high overhead of moving the lines themselves
Tuesday, May 24, 2011
5.5 Character Pointers and Functions
- Strcpy ( ) function:
- strcmp ( ) function:
- *--p decrements p before fetching the character that p points to
- Standard idioms for pushing and popping stack:
Monday, May 23, 2011
5.4 Address Arithmetic
- C's integration of pointers, arrays and address arithmetic is one of the strengths of the language
- alloc(n), returns a pointer p to n-consecutive character positions, which can be used by the caller of alloc for storing character
- afree(n) releases the storage thus acquired so it can be re-used later
- Storage managed by alloc and afree is a stack or last-in, first-out list
- In general, a pointer can be initialized to zero or an expression involving the addresses of previously defined data of appropriate type
- C guarantees that zero is never a valid address of data, so a return value of zero signal an abnormal event
- Pointers and integers are not interchangeable
- Zero is sole exception: the constant zero may be assigned to a pointer, and a pointer may be compared with the constant zero
- The construction p+n means the address of the n-th object beyond the one p currently points to
- n is scaled according to the size of the objects p points to, which is determined by the declaration of p.
- The valid pointer operations are assignment of pointers of the same type, adding or subtracting a pointer and an integer, subtracting or comparing two pointers to members of the same array, and assigning or comparing to zero
Thursday, May 19, 2011
5.3 Pointers and Arrays
- For pa = &a[0]
- a[i] can also be written as *(a+i); &a[i] = a+i
- A pointer is a variable, so pa = a and pa++ is legal
- An array name is not a variable, so a = pa and a++ is illegal
- When an array name is passed to a function, what is passed is the location of the initial element
- Within the called function, this argument is a local variable, and so an array name parameter is a pointer(variable containing an address)
- As formal parameters in a function definition, char s[] and char *s are equivalent
- It is possible to pass part of an array to a function, by passing a pointer to the beginning of the subarray
Tuesday, May 17, 2011
5.2 Pointers and Function Arguments
- Since C passes arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function
- Because of call-by-value, function below only swaps copies of a and b:
- The way to obtain the desired effect is for calling program to pass pointers to the value to be changed:
- Pointer arguments enable a function to access and change objects in the function that called it
Monday, May 16, 2011
5.1 Pointers and Addresses
- A typical machine has an array of consecutively numbered or addressed memory cells that may be manipulated individually or in contiguous groups
- The unary operator & gives the address of an object
- & operator only applies to objects in memory: variables and array elements
- The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it accesses the object the pointer points to
- Example:
Chapter 5: Pointers and Arrays
- A pointer is a variable that contains the address of a variable
- Pointers and arrays are closely related
Thursday, March 24, 2011
4.11 The C Preprocessor
- C provides certain language facilities by means of a preprocessor, which is conceptually a separate first step in compilation
- Two most frequently used features are #include and #define
- #include includes the contents of a file during compilation
- #define replace a token by an arbitrary sequence of characters.
Wednesday, March 23, 2011
4.10 Recursion
- A function may call itself either directly or indirectly
- Example of recursion function: printd, quicksort
4.9 Initialization
- In the absence of explicit initialization, external and static variables are initialized to zero; automatic and register variables have undefined/garbage initial values
- For external and static variable, initializer must be a constant expression; initialization is done once, before the program begins execution
- For automatic and register variable, initializer is not restricted to be a constant expression, it can be previously defined values or function calls; initialization is done each time the function or block is entered
- An array may be initialized by following its declaration with a list of initializers enclosed in braces and separated by commas. ie:
- When the size of array is omitted, compiler will compute the length by counting the initializers
- For character arrays initialization, a string may be used instead of the braces and commas notation:
Tuesday, March 22, 2011
4.7 Register Variables
- A register declaration advises the compiler that the variable in question will be heavily used
- Register variables are to be placed in machine registers which may result in smaller and faster programs. ( but compilers are free to ignore the advice)
- Register declaration can only be applied to automatic variables and to the formal parameters of a function
4.6 Static Variables
- The static declaration, applied to an external variable or function, limits the scope of that object to the rest of the source file being compiled
- If a variable or function is declared static, its name is invisible outside the file in which it is declared
- Internal static variables provide private, permanent storage within a single function
4.4 Scope Rules
- The scope of a name is the part of the program within which the name can be used
- For an automatic variable declared at the beginning of a function, the scope is the function in which the name is declared. Local variables of the same name in different functions are unrelated
- The scope of an external variable or a function lasts from the point at which it is declared to the end of the file being compiled
- It is important to distinguish between the declaration of an external variable and its definition
- A declaration announces the properties of an external variable (primarily its type) (ie. extern int a;)
- A definition also cause storage to be set aside (ie. int a;)
- Array size must be specified with the definition, but are optional with an extern declaration
- Initialization of an external variable goes only with the definition
- Example:
Monday, March 21, 2011
4.3 External Variables
- External variables and functions have the property that all references to them by the same name are references to the same thing. (external linkage)
Friday, March 18, 2011
4.2 Functions Returning Non-integers
- For functions returning non-integers
- Function must declare the type of value it returns (ie. double function ( ) )
- Calling routine must know that the function returns a non-int value
- Declarations must match definitions
- If functions take argument, declare them; if functions take no argument, use void
Thursday, March 17, 2011
Wednesday, March 16, 2011
Chapter 4 Functions and Program Structure
- Functions break large computing tasks into smaller ones, and enable people to build on existing program without starting from scratch
Tuesday, March 15, 2011
3.8 Goto and Labels
- Goto statement allows breaking out of two or more loops at once:
- A label has the same form as a variable name, and is followed by a colon
3.7 Break and Continue
- Break statement provides early exit from a loop (for, while, do and switch)
- Continue statement causes the next iteration of the enclosing for, while or do loop to begin
3.6 Loops - Do While
- Do syntax:
- Statement is executed, then the expression is evaluated. If expression is true, the cycle repeats
3.5 Loops - While and For
- While syntax:
- Expression is evaluated. If expression is true, statement is executed and expression is re-evaluated. Cycle continue until expression is zero
- for syntax:
Monday, March 14, 2011
3.4 Switch
- Switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly
- Syntax:
- case labeled default is executed if none of the cases are satisfied
- default is optional
- Example:
- Break statement causes an immediate exit from the switch
3.1 Statements and Blocks
Chapter 3 Control Flow
- Semicolon ; is a statement terminator ( ie. x = 0; )
- Braces { } are used to group declarations and statements into a compound statement or block
Thursday, March 10, 2011
2.12 Precedence and Order of Evaluation
- C does not specified the order of operands of an operator are evaluated. (exception ?: etc)
- C does not specified the order of function arguments are evaluated
- Function calls, nested assignment statements, and increment and decrement operators cause " side effects" - some variables are changed as a by-product of the evaluation of an expression
- ie. a[i] = i++; ( subscript is the old or new value of i? Different compliers, generate different answers, depending on machine architecture)
2.11 Conditional Expressions
- Conditional expression written with ternary operator " ?:" ( expr1 ? expr2 : expr3 )
- expr1 is evaluated, if expr1 is true then expr2 is evaluated, otherwise expr3 is evaluated (ie. z = (a > b) ? a : b; /* z = max (a,b) */ )
2.10 Assignment Operators and Expressions
- Assignment Operators: += (ie. i = i + 2 can be written as i += 2)
- Most binary operators have a corresponding assignment operator op = (op: + - * / % << >> & ^ | )
- expr1 op = expr2 equal to expr1 = (expr1) op (expr2)
Wednesday, March 9, 2011
2.9 Bitwise Operators
- Six operators for bit manipulation:
- The operators can only be applied to integral operands - int, char, short and long (signed or unsigned)
- bitwise AND operator is often used to mask off some set of bits
- bitwise inclusive OR operator is used to turn bits on
- bitwise exclusive OR operator set a one in each bit position where its operands have different bits, and zero where they are the same
- Shift operator shift the bit position of operand and fill vacated bits with zero
- Unary operator yields the one's complement of an integer (convert each 1-bit into 0-bit and vice versa)
2.8 Increment and Decrement Operators
- Increment operators ++ add 1 to the operand while decrement operator -- subtract 1 from the operand
- ++ and -- can be used as prefix or postfix operators, effect might be different depending on use cases
- The expression ++n increment n before its value is used, while the expression n++ increment after its value is used
- ++ and -- can only be applied to variables
2.7 Type Conversions
- When an operator has operands of different types, they are converted to a common type according to a small number of rules
- In general, the only automatic conversions are those that convert a "narrower" operand to a "wider" operand, without loss of information ( ie. integer to floating point)
2.6 Relational and Logical Operators
- Relational operators (same precedence): >, >=, <, <=
- Equality operators (lower precedence than relational): = =, ! =
- Relational operators have lower precedence than arithmetic
- Logical operators (evaluated left to right): && , | |
- Precedence of && is higher than ||
- Logical operators' precedence is lower than equality and relational
- Unary negation operator ! convert a non-zero operand into 0 and a zero operand into 1 (ie. !valid)
Monday, March 7, 2011
2.5 Arithmetic Operators
- Binary arithmetic operators are: +, -, *, /
- Integer division truncates any fractional part
- Modulus operator: %
- x % y produce the remainder when x is divided by y (zero when y divides x exactly)
- The % modulus operator cannot be applied to float or double
- The direction of truncation for / and the sign of the result for % are machine-dependent for negative operands
- Precedence (lowest first) : + -, * / %, unary + -
- Arithmetic operators associate left to right
Friday, March 4, 2011
2.4 Declarations
- All variables must be declared before use. (certain declarations can be made implicitly by context)
- A declaration specifies a type and a list of one or more variables associated with the type
- A variable may also be initialized in its declaration
- An explicitly initialized automatic variable is initialized each time its function/block is entered
- External and static variables are initialized to zero by default
- Automatic variables with no explicit initializer has undefined (ie. garbage) value
- The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (ie. const double e = 2.718)
Thursday, March 3, 2011
2.3 Constants
- A long constant is written with a terminal l or L (ie. 123456789L)
- An unsigned constant is written with a terminal u or U
- The suffix ul or UL indicates unsigned long
- Floating-point constants contain a decimal point (123.4) or an exponent (1e-2) (double type unless suffixed)
- The suffix f or F indicates floating constant
- A leading 0 on an integer constant means octal
- A leading 0x on an integer constant means hexadecimal
- A character constant is an integer written as one character within single quotes (ie. 'x')
- The value of character constant is the numeric value of the characters in the machine's character set (ie '0' has the value 48 in ASCII character set
- Certain characters can be represented in character and string constants by escape sequences like \n newline
- Complete set of escape sequence:
- Character constant ' \0 ' represents the character with value zero - the null character
- A string constant/literal is a sequence of zero or more characters surrounded by double quotes. ( ie. " Hello World" )
- The internal representation of a string has a null character ' \0 ' at the end, so the physical storage required is one more than the written characters length
- An enumeration is a list of constant integer values
- The first name in an enum has value 0, the next 1, and so on, unless explicit values are specified
- If not all values are specified, unspecified value continue progression from the last value
- Enumeration associate constant value with name, an alternative to #define with auto-value generation advantage
Tuesday, March 1, 2011
2.2 Data Types and Sizes
- Basic data types:
- short and long (qualifiers) apply to integer data type
- int will normally be the natural size of a particular machine
- short is often 16 bit; long is 32 bit, integer can be 16 or 32 bits
- signed and unsigned (qualifiers) apply to char and int
- Unsigned numbers are always positive or zero and obey the laws of arithmetic modulo 2^n, where n is the number of bits in the type
- long double specifies extended-precision floating points
- The standard headers <limits.h> and <float.h> contain symbolic constants for all of these sizes
Chp 2 Types, Operators, and Expressions
- Variables and constants are basic data objects manipulated in a program.
- Declarations list the variables to be used, and state what types and initial values if any
- Operators specify what is to be done to the data objects
- The type of an object determine its set of values and what operations to be performed
- 2.1 Variable Names
- Names are made up of letters and digits; first character must be a letter
- Underscore "_" counts as a letter
- Upper and lower case letters are distinct
- Traditional C practice is to use lower case for variable name and all upper case for symbolic constants
Monday, January 31, 2011
1.10 External Variables and Scope
- Variables (automatic) in a function are local or private to the particular function
- Each local variable in a function comes into existence only when the function is called, and disappeared when the function exited
- Automatic variables do not retain their values from one call to the next, and must be explicitly set upon each entry. If they are not set, they will contain garbage
- External variables are globally accessible, exist permanently and retain values after function returned, oppose to automatic variables
- An external variable must be defined, exactly once, outside of any function; to set aside storage for it
- The external variable must also be declared in each function that want to access it; this states the type of the variable. The declaration may be an explicit "extern" statement or may be implicit from context
- If the definition of an external variable occurs in the source file before its use in a particular function, then there is no need for an extern declaration in the function
- Common practice is to place definition of all external variables at the beginning of source files and then omit all extern declarations
- If a program is in several source files, and a variable is defined in file1 and used in file2 and file3, then the extern declarations are needed in file2 and file3 to connect the occurrences of the variable
- The usual practice is to collect extern declaration of variables and functions in a separate file (header)
Thursday, January 27, 2011
Wednesday, January 26, 2011
1.8 Arguments - Call by Value
- All functions arguments are passed "by value": called function is given the value of its arguments in temporary variables rather than originals
- Called function cannot directly alter a variable in the calling function
- Call by reference: the called routine has access to the original argument, not a local copy
- It is possible to arrange for a function to modify a variable in a calling routin. The caller must provide the address of the variable to be set (a pointer to the variable)
- The called function must declare the parameter to be a pointer.
- Call by value leads to more compact programs with fewer extraneous variables, because parameters can be treated as initialized local variables in the called routine
- To modify a variable in a calling function, the caller must provide the address of the variable to be set (pointer to the variable), and the called function must declare the parameter to be a pointer, and access the variable indirectly through it
- In contrast, when the name of an array is used as an argument in a calling function, the value passed to the calling function is the location or address of the beginning of the array - there is no copying of array elements
- By subscripting this value, the function can access and alter any element of the array
Tuesday, January 25, 2011
1.7 Functions
- A function provides a convenient way to encapsulate some computation, which can then be used without worrying about its implementation
- Function definition:
- Function definitions declare the parameter types and names, and the type of the result that the function returns ie. int power (int base, int n)
- Function definitions can appear in any order, and in one source file or several, although no function can be split between files.
- Power function exm:
- Generally use parameter for a variable named in the parenthesized list in a function definition, and argument for the value used in a call of the function
- The name used by function definition for its parameters are local to the function definition, and are not visible to any other function
- The value that function definition computes is returned to main function by the return expression
- A function need not return a value; a return statement with no expression cause control, but no useful value, to be returned to the caller
- In main function, a return value of zero implies normal termination; non-zero values implies erroneous termination condition
- Function prototype example: int power (int m, int n); expect two int arguments and returns an int
- Function prototype declaration has to agree with the definition and uses of functions parameter names are optional in a function prototype.
Subscribe to:
Posts (Atom)