Difference between revisions of "C language"
Jump to navigation
Jump to search
(→Basics) |
|||
| (48 intermediate revisions by 5 users not shown) | |||
| Line 2: | Line 2: | ||
Sources | Sources | ||
* [http://robertseacord.com/wp/errata/ Effective C ]by Robert Seacord | * [http://robertseacord.com/wp/errata/ Effective C ]by Robert Seacord | ||
| − | * 21st Century C | + | * [https://www.oreilly.com/library/view/21st-century-c/9781449344382/ 21st Century C] by Ben Clemens |
| − | * | + | * [https://shop.learncodethehardway.org/products/contents/3/ Learn C the Hard Way] by Zed Shaw |
| + | * [https://link.springer.com/book/10.1007/978-1-4842-6128-6 Practical Numerical C Programming] and [https://learning.oreilly.com/library/view/numerical-c-applied/9781484250648/ Numerical C] by Philip Joyce | ||
| + | * [https://link.springer.com/book/10.1007/978-1-4842-6927-5 Pointers in C Programming] by Thomas Mailund | ||
| + | * [https://www.packtpub.com/product/learn-c-programming-second-edition/9781801078450 Learn C Programming] by Jeff Szuhay | ||
| + | * [https://www.packtpub.com/product/practical-c-programming/9781838641108 Practical C Programming] by B.M. Harwani | ||
| + | * [https://github.com/Apress/practical-c Practical C] by Giulio Zambon (2016) | ||
| + | * Modern C by Jens Gustedt | ||
===Basics=== | ===Basics=== | ||
| + | From ''Effective C'' by Robert Seacord | ||
;Objects, Functions, Types and Pointers | ;Objects, Functions, Types and Pointers | ||
| − | * '''object''': storage used to represent values. (Per ISO/IEC 9989:2018: "a region of data storage in the execution environment, the contents of which can represent values. A '''variable''' is an example of an object. An object with '''type''' <code>int</code> contains and integer value. | + | * '''object''': storage used to represent values. (Per ISO/IEC 9989:2018: "a region of data storage in the execution environment, the contents of which can represent values. A '''variable''' is an example of an object. An object with '''type''' <code>int</code> contains and integer value. E.g. why types are important: the ''text'' number 1 in IEEE 754 (ASCII, roughly) is specified by 0x3f80000, which a little over a billion as a decimal. |
| − | E.g. why types are important: the ''text'' number 1 in IEEE 754 (ASCII, roughly) is specified by 0x3f80000, which a little over a billion as a decimal. | ||
* '''functions''': are not objects, but do have types. A function is defined by both its return type and the number and types of its parameters. | * '''functions''': are not objects, but do have types. A function is defined by both its return type and the number and types of its parameters. | ||
| − | * '''types''': | + | * '''types''': <code>int, char, bool, float, long int...</code> |
* '''pointers''': an address or location in memory where an object or function is stored. Pointer types derive from the ''referenced'' function. or object type. E.g., <code>*char</code> is called a ''pointer to char''. | * '''pointers''': an address or location in memory where an object or function is stored. Pointer types derive from the ''referenced'' function. or object type. E.g., <code>*char</code> is called a ''pointer to char''. | ||
* Because objects and functions are different things, object pointers differ from function pointers | * Because objects and functions are different things, object pointers differ from function pointers | ||
| − | * In the swap program below the <code>main</ | + | * In the swap program below the <code>main</code> function declares two variables of type <code>int</code>, using the combination of a type (int), an identifier (a,b) and a value (21,17). Assigning the values is also called ''initialization |
* '''parameters''': objects declared as part of a function declaration that acquire value on entry to the function | * '''parameters''': objects declared as part of a function declaration that acquire value on entry to the function | ||
* '''argruments''': comma-separated expressions included in the function call expression (whether values or pointers) | * '''argruments''': comma-separated expressions included in the function call expression (whether values or pointers) | ||
| − | * '''pass-by- | + | * '''pass-by-value''': C's default behavior. When you provide an argument to a function, its value is copied into a distinct variable for use within that function. When the values of the parameters are changed, the values in the caller are unaffected because they are distinct objects. |
<syntaxhighlight lang=C> | <syntaxhighlight lang=C> | ||
| Line 41: | Line 47: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| − | The commented lines in the <code>swap</code> function show the original program, which failed to swap <code>main</code>'s values, because they were being passed by value rather than reference. The corrected version (above) declares and dereferences pointers with the '''indirection''' operator (*) | + | * The commented lines in the <code>swap</code> function show the original program, which failed to swap <code>main</code>'s values, because they were being passed by value rather than reference. The corrected version (above) declares and dereferences pointers with the '''indirection''' operator (*) |
| − | + | * In the new version, the line <code>*pa=*pb</code> serves to: | |
| − | * | + | # deference the pointer <code>pb</code> |
| − | + | # reads the referenced value | |
| − | + | # dereference the pointer <code>pa</code> | |
| − | + | # overwrite the value at the location referenced by <code>pa</code> with the value referenced by <code>pb</code> | |
| + | * in the main function, <code>&a</code> , the unary & operator (''address-of'' operator) generates a pointer to its operand. | ||
| Line 63: | Line 70: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| + | |||
| + | * '''Scope/Lifetime''': scope applies to identifiers, lifetime applies to objects | ||
| + | * '''Storage duration''': automatic, static, thread, allocated | ||
| + | * '''Alignment''': object types have restrictions on the addresses at which they may be stored. an ''alignment'' is the number of bytes between successive addresses at which a given object can be allocated. Traditionally done with linker commands or overallocating memory with <code>malloc</code>, followed by rounding the address up to nearest power of 2. | ||
| + | * C11 sorted most of this out. Alignments are values of type <code>size_t</code>. Valid assignments are non-negative powers of 2. | ||
| + | |||
| + | <syntaxhighlight lang=C> | ||
| + | struct S { | ||
| + | int i; double d; char c; | ||
| + | }; | ||
| + | int main(void) { | ||
| + | unsigned char bad_buff[sizeof(struct S)]; | ||
| + | _Alignas(struct S) unsigned char good_buff[sizeof(struct S)]; | ||
| + | struct S *bad_s_ptr = (struct S *)bad_buff; // wrong pointer alignment | ||
| + | struct S *good_s_ptr = (struct S *)good_buff; // correct pointer alignment | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | In the above code | ||
| + | |||
| + | ;Object Types | ||
| + | * Boolean: declare as <code>bool</code>; contains either 0 or 1. (Also denoted <code>_Bool</code> | ||
| + | * Character: <code> char, signed char, unsigned char</code> | ||
| + | * Numeric: <code>signed char, short int, int, long, long long int</code>. For each there is a corresponding unsigned type that uses the same amount of storage (but obviously only 1/2 the range on the positive side). | ||
| + | * Enumerations: allows type definition by assigning names ("enumerators") to integer values. E.g., {S,M,T,W,Th,F,Sa} | ||
| + | * Floating-point: <code>float, double, long double</code>. | ||
| + | * void: the keyword <code>void</code> means "cannot hold any value". However, <code>void *</code> means the pointer can reference ''any'' object. | ||
| + | ;Function Types | ||
| + | * types are all derived. Name and return type are specified by the ''function declarator''. Parameter types must be specified unless of type <code>void</code> | ||
| + | <syntaxhighlight lang=C> | ||
| + | int max(int a, int b) | ||
| + | { return a > b ? a : b; } | ||
| + | </syntaxhighlight> | ||
| + | * Here is a function that returns an <code>int</code>. The declarator is <code>max(int a, int b)</code> and the function body is the 2nd line | ||
| + | * The function specification (line 2) may not include any type qualifiers (e.g., int, char, etc.) | ||
| + | |||
| + | ;Derived Types | ||
| + | pointers, arrays, type definitions, structures and unions | ||
| + | *'''Pointers''': derived from the function or object it points to, which is the ''referenced'' type. E.g., <code>int i= 17; int *ip = &i;</code>, | ||
| + | declares the variable <code>ip</code> as a pointer to int and assigns it the address of i. '''The unary * operator converts a pointer to a type into a value of that type.''' Consider <code>ip = &*ip;</code>. Here * is ''dereferencing'' <code>ip</code>. It takes the address using & and retrieves the pointer. | ||
| + | * '''Arrays''': contiguously allocated sequence of objects of the same type. E.g. <code>int ia[11], float *afp[17];</code>. To declare a matrix, use something like <code>int arr[3][5];</code> | ||
| + | |||
| + | <syntaxhighlight lang=C> | ||
| + | void func(int arr[5]); | ||
| + | int main(void) { | ||
| + | unsigned int i = 0; | ||
| + | unsigned int j = 0; | ||
| + | int arr[3][5]; | ||
| + | u func(arr[i]); | ||
| + | v int x = arr[i][j]; | ||
| + | return 0; | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | What's happening? | ||
| + | When the function calls <code>arr[i]</code>, a bunch of shit happens: | ||
| + | # <code>arr</code> is converted to a pointer to the initial 5-element int array, starting at <code>arr[i]</code> | ||
| + | # <code>i</code> is scaled to the type of <code>arr</code> by multiplying it by the size of one array of 5 int objects | ||
| + | # The results from the above are added | ||
| + | # Indirection is applied to the result to produce an array of 5 int elements | ||
| + | |||
| + | ====Structures==== | ||
| + | * contain sequentially allocated memory objects | ||
| + | * objects have their own names and may or may not share the same type (unlike arrays, which are monotyyped); similar to records | ||
| + | * below, the structure contains 3 objects, <code>signum, signame, sigdesc</code> | ||
| + | * the last line identifies the whole object as <code>sigline</code> and having a pointer of <code>*sigline_p</code> | ||
| + | |||
| + | <syntaxhighlight lang=C> | ||
| + | struct sigrecord { | ||
| + | int signum; | ||
| + | char signame[20]; | ||
| + | char sigdesc[100]; | ||
| + | } sigline, *sigline_p; | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | * Now that the struct has been created we'd like to reference its members, using the "structure member operator (<math>\cdot</math>"; like the dot operator in Python and other langs). | ||
| + | * a pointer to a struct can reference its members with the (->) structure pointer operator | ||
| + | * the first 3 lines directly access members of the <code>sigline</code> object. The middle line assigns its address to the <code>sigline_p</code> pointer. | ||
| + | * the last 3 lines indirectly access members of the struct. | ||
| + | <syntaxhighlight lang=C> | ||
| + | sigline.signum = 5; | ||
| + | strcpy(sigline.signame, "SIGINT"); | ||
| + | strcpy(sigline.sigdesc, "Interrupt from keyboard"); | ||
| + | |||
| + | sigline_p = &sigline; | ||
| + | |||
| + | sigline_p->signum = 5; | ||
| + | strcpy(sigline_p->signame, "SIGINT"); | ||
| + | strcpy(sigline_p->sigdesc, "Interrupt from keyboard"); | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | ; Unions | ||
| + | * Similar to structs, but memory for member objects overlaps | ||
| + | * Primarily used to conserve memory and used to contain mixed types (e.g., ints and floats) | ||
| + | * access elements with dot operator; reference members with the -> operator | ||
| + | |||
| + | ; Tags & typedefs | ||
| + | * naming mechanism for structs, unions and enumerations | ||
| + | * declare a tag for a struct s: <code>struct s <mytag></code> | ||
| + | * use a <code>typedef</code> to declare an alias for an existing type, without creating a new type | ||
| + | * here's an example: | ||
| + | <syntaxhighlight lang=C> | ||
| + | typedef signed char schar_type, *schar_p, (*fp)(void); | ||
| + | </syntaxhighlight> | ||
| + | * declare schar_type as an alias for signed char. schar_p as an alias for signed char*, and fp as an alias for signed char(*)(void). | ||
| + | |||
| + | ===Basic Values and Data (Gustedt Ch5)=== | ||
| + | * values are ''observable'' only if they are stored in ''addressable'' memory or written to output. C compilers produce an executable that reproduces only the ''observable states''. The whole mechanism is an '''abstract state machine'''. | ||
| + | * All values are numbers or translate into numbers. The ''data'' of a program execution consists of all the assembled values of all objects at a given moment. | ||
| + | * The '''state''' of the program execution is determined by: | ||
| + | ** The executable | ||
| + | ** The current point of execution | ||
| + | ** The data | ||
| + | ** Outside intervention, such as I/O from the user | ||
| + | |||
| + | ====Types==== | ||
| + | * A '''type''' is a property that C associates with values. All values have a type that is statically determined | ||
| + | * Possible operations on a value are determined by its type; a value's type determines the results of all operations on it. | ||
| + | * C enforces that the results of operations can be deduced from 1) the operand values, and 2) some platform-specific characteristics. A type's '''binary representation''' determines the results of all operations, and this representation is observable. | ||
| + | * The binary representation is a model and therefore an ''abstract'' representation (insofar as it doesn't determine where or how values are stored). The bare metal aspects are called the ''object representation''. | ||
| + | * All computation is fixed through the values, types and their binary representations specified in the program. The program code describes an '''abstract state machine''', which governs its state transitions. | ||
| + | * Types broadly determine compiler optimizations. The main types are: | ||
| + | # unsigned integers (_Bool, unsigned char, short, int, long, long long) | ||
| + | # signed integers (char, signed char, short, int, long, long long) | ||
| + | # real floats (float, double, long double) | ||
| + | # complex floats (float _Complex, double _Complex, long double _Complex) | ||
| + | * The six "narrow types"---bool, unsigned char, unsigned short, char, signed char, signed short--must be "promoted" in order to perform arithmetic. Before arithmetic, narrow types are promoted to <code>signed int</code> type. | ||
| + | * For any type (or "rank"), the non-negative (i.e., positive) values of the signed type fit into the unsigned types. E.g., unsigned ints range from 0 to 4,294,967,295, so any positive number in the ''signed'' range-- -2,147,483,648 to 2,147,483,647--automatically fits into the unsigned version of the same type. | ||
| + | ;Which type for which occasion? | ||
| + | * <code>size_t</code> for sizes, cardinalities and ordinals | ||
| + | * <code>unsigned</code> for small, non-negative quantities | ||
| + | * <code>ptrdiff_t</code> for large, signed differences | ||
| + | * <code> double</code> for floating-point calculations; <code>double complex</code> for complex calculations | ||
| + | ;Various Constant Specifications | ||
| + | {| class="wikitable" | ||
| + | |- | ||
| + | ! Type | ||
| + | ! E.g. | ||
| + | ! For | ||
| + | |- | ||
| + | | Decimal int | ||
| + | | 123 | ||
| + | | general use | ||
| + | |- | ||
| + | | Octal int | ||
| + | | 077 | ||
| + | | rarely used | ||
| + | |- | ||
| + | | Hex int | ||
| + | | 0xffff | ||
| + | | | ||
| + | |- | ||
| + | | Decimal float | ||
| + | | 1.7E-13 | ||
| + | | | ||
| + | |- | ||
| + | | Hex float | ||
| + | | 0x1.7aP-13 | ||
| + | | | ||
| + | |- | ||
| + | | Integer char | ||
| + | | "a" | ||
| + | | | ||
| + | |- | ||
| + | | String literals | ||
| + | | "hello" | ||
| + | | | ||
| + | |} | ||
| + | |||
| + | *String formatting specifiers can be found [https://www.tutorialspoint.com/format-specifiers-in-c here] | ||
| + | ====Specifying Values==== | ||
| + | * Numeric constants (literals) can be specified as one of the following: decimal integer, octal integer, hexadecimal integer, decimal float, hexadecimal float, integer character ('a'), string literal ('hello') | ||
| + | * Numerical literals are never negative; instead they are operated on by unary minus (-). | ||
| + | * A ''decimal integer constant'' has the first of the 3 signed types that fits it. E.g., 32768 (<math>2^{15}+1</math>) doesn't fit into <code>signed int</code>, and is thus a <code>signed long</code> | ||
| + | * Objects of <code>const</code>-qualified type are read-only, as are string literals | ||
| + | * enumeration constants are of type <code>signed int</code>. They have either an explicit or positional value | ||
| + | * Integer constant expressions (ICE) | ||
| + | <syntaxhighlight lang=C> | ||
| + | signed const o42 = 42; | ||
| + | enum { | ||
| + | b42 = 42, // ok, 42 is a literal | ||
| + | c52 = o42 + 10 // Not ok: o42 is an object | ||
| + | b52 = b42 + 10 // ok, b42 is not an object | ||
| + | </syntaxhighlight> | ||
| + | * A '''macro''' provides textual replacement of the program code, introduced by the <code>#define</code> keyword | ||
| + | * [The macro example on p.55 doesn't even remotely work] | ||
| + | |||
| + | |||
| + | ===Effective C=== | ||
| + | *Bitwise operators: AND (&), XOR (^), OR (|) | ||
| + | *Logical operators: AND (&&), OR (||) | ||
| + | *Cast operators: aka typecasting. Precede an expression with parenthesized type name: <code> int sum = (int)x + 1; </code> | ||
| + | *Conditional operator: <code> result = condition ? valueReturnedIfTrue : valueReturnedIfFalse; </code>. Example: <code> const int x = (a < b) ? b : a; </code> | ||
Latest revision as of 18:59, 4 April 2022
Elements of C[edit]
Sources
- Effective C by Robert Seacord
- 21st Century C by Ben Clemens
- Learn C the Hard Way by Zed Shaw
- Practical Numerical C Programming and Numerical C by Philip Joyce
- Pointers in C Programming by Thomas Mailund
- Learn C Programming by Jeff Szuhay
- Practical C Programming by B.M. Harwani
- Practical C by Giulio Zambon (2016)
- Modern C by Jens Gustedt
Basics[edit]
From Effective C by Robert Seacord
- Objects, Functions, Types and Pointers
- object: storage used to represent values. (Per ISO/IEC 9989:2018: "a region of data storage in the execution environment, the contents of which can represent values. A variable is an example of an object. An object with type
intcontains and integer value. E.g. why types are important: the text number 1 in IEEE 754 (ASCII, roughly) is specified by 0x3f80000, which a little over a billion as a decimal. - functions: are not objects, but do have types. A function is defined by both its return type and the number and types of its parameters.
- types:
int, char, bool, float, long int... - pointers: an address or location in memory where an object or function is stored. Pointer types derive from the referenced function. or object type. E.g.,
*charis called a pointer to char. - Because objects and functions are different things, object pointers differ from function pointers
- In the swap program below the
mainfunction declares two variables of typeint, using the combination of a type (int), an identifier (a,b) and a value (21,17). Assigning the values is also called initialization
- parameters: objects declared as part of a function declaration that acquire value on entry to the function
- argruments: comma-separated expressions included in the function call expression (whether values or pointers)
- pass-by-value: C's default behavior. When you provide an argument to a function, its value is copied into a distinct variable for use within that function. When the values of the parameters are changed, the values in the caller are unaffected because they are distinct objects.
#include <stdio.h>
void swap(int *pa, int *pb) {
int t = *pa;
*pa = *pb;
*pb = t;
// int t = a;
//a = b;
//b = t;
printf("swap: a = %d, b = %d\n", *pa,*pb);
}
int main(void){
int a = 21;
int b = 17;
swap(&a, &b);
printf("main: a = %d, b = %d\n", a, b);
return 0;
}
- The commented lines in the
swapfunction show the original program, which failed to swapmain's values, because they were being passed by value rather than reference. The corrected version (above) declares and dereferences pointers with the indirection operator (*) - In the new version, the line
*pa=*pbserves to:
- deference the pointer
pb - reads the referenced value
- dereference the pointer
pa - overwrite the value at the location referenced by
pawith the value referenced bypb
- in the main function,
&a, the unary & operator (address-of operator) generates a pointer to its operand.
void increment(void) {
static unsigned int counter = 0;
counter++;
printf("%d", counter);
}
int main(void) {
for (int i = 0; i < 5; i++) {
increment();
}
return 0;
}
- Scope/Lifetime: scope applies to identifiers, lifetime applies to objects
- Storage duration: automatic, static, thread, allocated
- Alignment: object types have restrictions on the addresses at which they may be stored. an alignment is the number of bytes between successive addresses at which a given object can be allocated. Traditionally done with linker commands or overallocating memory with
malloc, followed by rounding the address up to nearest power of 2. - C11 sorted most of this out. Alignments are values of type
size_t. Valid assignments are non-negative powers of 2.
struct S {
int i; double d; char c;
};
int main(void) {
unsigned char bad_buff[sizeof(struct S)];
_Alignas(struct S) unsigned char good_buff[sizeof(struct S)];
struct S *bad_s_ptr = (struct S *)bad_buff; // wrong pointer alignment
struct S *good_s_ptr = (struct S *)good_buff; // correct pointer alignment
}
In the above code
- Object Types
- Boolean: declare as
bool; contains either 0 or 1. (Also denoted_Bool - Character:
char, signed char, unsigned char - Numeric:
signed char, short int, int, long, long long int. For each there is a corresponding unsigned type that uses the same amount of storage (but obviously only 1/2 the range on the positive side). - Enumerations: allows type definition by assigning names ("enumerators") to integer values. E.g., {S,M,T,W,Th,F,Sa}
- Floating-point:
float, double, long double. - void: the keyword
voidmeans "cannot hold any value". However,void *means the pointer can reference any object.
- Function Types
- types are all derived. Name and return type are specified by the function declarator. Parameter types must be specified unless of type
void
int max(int a, int b)
{ return a > b ? a : b; }
- Here is a function that returns an
int. The declarator ismax(int a, int b)and the function body is the 2nd line - The function specification (line 2) may not include any type qualifiers (e.g., int, char, etc.)
- Derived Types
pointers, arrays, type definitions, structures and unions
- Pointers: derived from the function or object it points to, which is the referenced type. E.g.,
int i= 17; int *ip = &i;,
declares the variable ip as a pointer to int and assigns it the address of i. The unary * operator converts a pointer to a type into a value of that type. Consider ip = &*ip;. Here * is dereferencing ip. It takes the address using & and retrieves the pointer.
- Arrays: contiguously allocated sequence of objects of the same type. E.g.
int ia[11], float *afp[17];. To declare a matrix, use something likeint arr[3][5];
void func(int arr[5]);
int main(void) {
unsigned int i = 0;
unsigned int j = 0;
int arr[3][5];
u func(arr[i]);
v int x = arr[i][j];
return 0;
}
What's happening?
When the function calls arr[i], a bunch of shit happens:
arris converted to a pointer to the initial 5-element int array, starting atarr[i]iis scaled to the type ofarrby multiplying it by the size of one array of 5 int objects- The results from the above are added
- Indirection is applied to the result to produce an array of 5 int elements
Structures[edit]
- contain sequentially allocated memory objects
- objects have their own names and may or may not share the same type (unlike arrays, which are monotyyped); similar to records
- below, the structure contains 3 objects,
signum, signame, sigdesc - the last line identifies the whole object as
siglineand having a pointer of*sigline_p
struct sigrecord {
int signum;
char signame[20];
char sigdesc[100];
} sigline, *sigline_p;
- Now that the struct has been created we'd like to reference its members, using the "structure member operator ([math]\displaystyle{ \cdot }[/math]"; like the dot operator in Python and other langs).
- a pointer to a struct can reference its members with the (->) structure pointer operator
- the first 3 lines directly access members of the
siglineobject. The middle line assigns its address to thesigline_ppointer. - the last 3 lines indirectly access members of the struct.
sigline.signum = 5;
strcpy(sigline.signame, "SIGINT");
strcpy(sigline.sigdesc, "Interrupt from keyboard");
sigline_p = &sigline;
sigline_p->signum = 5;
strcpy(sigline_p->signame, "SIGINT");
strcpy(sigline_p->sigdesc, "Interrupt from keyboard");
- Unions
- Similar to structs, but memory for member objects overlaps
- Primarily used to conserve memory and used to contain mixed types (e.g., ints and floats)
- access elements with dot operator; reference members with the -> operator
- Tags & typedefs
- naming mechanism for structs, unions and enumerations
- declare a tag for a struct s:
struct s <mytag> - use a
typedefto declare an alias for an existing type, without creating a new type - here's an example:
typedef signed char schar_type, *schar_p, (*fp)(void);
- declare schar_type as an alias for signed char. schar_p as an alias for signed char*, and fp as an alias for signed char(*)(void).
Basic Values and Data (Gustedt Ch5)[edit]
- values are observable only if they are stored in addressable memory or written to output. C compilers produce an executable that reproduces only the observable states. The whole mechanism is an abstract state machine.
- All values are numbers or translate into numbers. The data of a program execution consists of all the assembled values of all objects at a given moment.
- The state of the program execution is determined by:
- The executable
- The current point of execution
- The data
- Outside intervention, such as I/O from the user
Types[edit]
- A type is a property that C associates with values. All values have a type that is statically determined
- Possible operations on a value are determined by its type; a value's type determines the results of all operations on it.
- C enforces that the results of operations can be deduced from 1) the operand values, and 2) some platform-specific characteristics. A type's binary representation determines the results of all operations, and this representation is observable.
- The binary representation is a model and therefore an abstract representation (insofar as it doesn't determine where or how values are stored). The bare metal aspects are called the object representation.
- All computation is fixed through the values, types and their binary representations specified in the program. The program code describes an abstract state machine, which governs its state transitions.
- Types broadly determine compiler optimizations. The main types are:
- unsigned integers (_Bool, unsigned char, short, int, long, long long)
- signed integers (char, signed char, short, int, long, long long)
- real floats (float, double, long double)
- complex floats (float _Complex, double _Complex, long double _Complex)
- The six "narrow types"---bool, unsigned char, unsigned short, char, signed char, signed short--must be "promoted" in order to perform arithmetic. Before arithmetic, narrow types are promoted to
signed inttype. - For any type (or "rank"), the non-negative (i.e., positive) values of the signed type fit into the unsigned types. E.g., unsigned ints range from 0 to 4,294,967,295, so any positive number in the signed range-- -2,147,483,648 to 2,147,483,647--automatically fits into the unsigned version of the same type.
- Which type for which occasion?
size_tfor sizes, cardinalities and ordinalsunsignedfor small, non-negative quantitiesptrdiff_tfor large, signed differencesdoublefor floating-point calculations;double complexfor complex calculations
- Various Constant Specifications
| Type | E.g. | For |
|---|---|---|
| Decimal int | 123 | general use |
| Octal int | 077 | rarely used |
| Hex int | 0xffff | |
| Decimal float | 1.7E-13 | |
| Hex float | 0x1.7aP-13 | |
| Integer char | "a" | |
| String literals | "hello" |
- String formatting specifiers can be found here
Specifying Values[edit]
- Numeric constants (literals) can be specified as one of the following: decimal integer, octal integer, hexadecimal integer, decimal float, hexadecimal float, integer character ('a'), string literal ('hello')
- Numerical literals are never negative; instead they are operated on by unary minus (-).
- A decimal integer constant has the first of the 3 signed types that fits it. E.g., 32768 ([math]\displaystyle{ 2^{15}+1 }[/math]) doesn't fit into
signed int, and is thus asigned long - Objects of
const-qualified type are read-only, as are string literals - enumeration constants are of type
signed int. They have either an explicit or positional value - Integer constant expressions (ICE)
signed const o42 = 42;
enum {
b42 = 42, // ok, 42 is a literal
c52 = o42 + 10 // Not ok: o42 is an object
b52 = b42 + 10 // ok, b42 is not an object
- A macro provides textual replacement of the program code, introduced by the
#definekeyword - [The macro example on p.55 doesn't even remotely work]
Effective C[edit]
- Bitwise operators: AND (&), XOR (^), OR (|)
- Logical operators: AND (&&), OR (||)
- Cast operators: aka typecasting. Precede an expression with parenthesized type name:
int sum = (int)x + 1; - Conditional operator:
result = condition ? valueReturnedIfTrue : valueReturnedIfFalse;. Example:const int x = (a < b) ? b : a;