c language notes
Section 1. Declarations and Initializations
1.1: How do you decide which integer type to use?
A: If you might need large values (tens of thousands), use long. Otherwise, if space is very important, use short. Otherwise, use int.
1.4: What should the 64-bit type on a machine that can support it?
A: C9X specifies long long.
1.7: What's the best way to declare and define global variables?
A: The best arrangement is to place each definition in some relevant .c file, with an external declaration in a header file.
1.11: What does extern mean in a function declaration?
A: Nothing, really; the keyword extern is optional here.
1.12: What's the auto keyword good for?
A: Nothing.
1.14: I can't seem to define a linked list node which contains a pointer to itself.
A: Structures in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this.
1.21: How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
A: char *(*(*a[N])())();
Using a chain of typedefs, or the cdecl program, makes these declarations easier.
1.22: How can I declare a function that returns a pointer to a function of its own type?
A: You can't quite do it directly. Use a cast, or wrap a struct around the pointer and return that.
1.25: My compiler is complaining about an invalid redeclaration of a function, but I only define it once.
A: Calling an undeclared function declares it implicitly as returning int.
1.25b: What's the right declaration for main()?
A: See questions 11.12a to 11.15.
1.30: What am I allowed to assume about the initial values of variables which are not explicitly initialized?
A: Uninitialized variables with "static" duration start out as 0, as if the programmer had initialized them. Variables with "automatic" duration, and dynamically-allocated memory, start out containing garbage (with the exception of calloc).
1.31: Why can't I initialize a local array with a string?
A: Perhaps you have a pre-ANSI compiler.
1.31b: What's wrong with "char *p = malloc(10);"?
A: Function calls are not allowed in initializers for global or static variables.
1.32: What is the difference between char a[] = "string"; and char *p = "string"; ?
A: The first declares an initialized and modifiable array; the second declares a pointer initialized to a not-necessarily- modifiable constant string.
1.34: How do I initialize a pointer to a function?
A: Use something like "extern int func(); int (*fp)() = func;" .
Section 2. Structures, Unions, and Enumerations
2.1: What's the difference between struct x1 { ... }; and typedef struct { ... } x2; ?
A: The first structure is named by a tag, the second by a typedef name.
2.2: Why doesn't "struct x { ... }; x thestruct;" work?
A: C is not C++.
2.3: Can a structure contain a pointer to itself?
A: See question 1.14.
2.4: What's the best way of implementing opaque (abstract) data types in C?
A: One good way is to use structure pointers which point to structure types which are not publicly defined.
2.6: I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make it act like the array had several elements. Is this legal or portable?
A: An official interpretation has deemed that it is not strictly conforming with the C Standard.
2.7: I heard that structures could be assigned to variables and passed to and from functions, but K&R1 says not.
A: These operations are supported by all modern compilers.
2.8: Is there a way to compare structures automatically?
A: No.
2.10: Can I pass constant values to functions which accept structure arguments?
A: Not yet. As of this writing, C has no way of generating anonymous structure values.
2.11: How can I read/write structures from/to data files?
A: It is relatively straightforward to use fread and fwrite.
2.12: How can I turn off structure padding?
A: There is no standard method.
2.13: Why does sizeof report a larger size than I expect for a structure type?
A: The alignment of arrays of structures must be preserved.
2.14: How can I determine the byte offset of a field within a structure?
A: ANSI C defines the offsetof() macro, which should be used if available.
2.15: How can I access structure fields by name at run time?
A: Build a table of names and offsets, using the offsetof() macro.
2.18: I have a program which works correctly, but dumps core after it finishes. Why?
A: Check to see if a structure type declaration just before main() is missing its trailing semicolon, causing main() to be declared as returning a structure. See also questions 10.9 and 16.4.
2.20: Can I initialize unions?
A: The current C Standard allows an initializer for the first-named member.
2.22: What is the difference between an enumeration and a set of preprocessor #define's?
A: At the present time, there is little difference. The C Standard states that enumerations are compatible with integral types.
2.24: Is there an easy way to print enumeration values symbolically?
A: No.
Section 3. Expressions
3.1: Why doesn't the code "a[i] = i++;" work?
A: The variable i is both referenced and modified in the same expression.
3.2: Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++);" prints 49. Regardless of the order of evaluation, shouldn't it print 56?
A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated.
3.3: What should the code "int i = 3; i = i++;" do?
A: The expression is undefined.
3.3b: Here's a slick expression: "a ^= b ^= a ^= b". It swaps a and b without using a temporary.
A: Not portably; its behavior is undefined.
3.4: Don't precedence and parentheses dictate order of evaluation?
A: Operator precedence and explicit parentheses impose only a partial ordering on the evaluation of an expression, which does not generally include the order of side effects.
3.5: But what about the && and || operators?
A: There is a special exception for those operators: left-to-right evaluation is guaranteed.
3.8: What's a "sequence point"?
A: A point (at the end of a full expression, or at the ||, &&, ?:, or comma operators, or just before a function call) at which all side effects are guaranteed to be complete.
3.9: So given a[i] = i++; we don't know which cell of a[] gets written to, but i does get incremented by one, right?
A: *No*. Once an expression or program becomes undefined, *all* aspects of it become undefined.
3.12: If I'm not using the value of the expression, should I use i++ or ++i to increment a variable?
A: Since the two forms differ only in the value yielded, they are entirely equivalent when only their side effect is needed.
3.14: Why doesn't the code "int a = 1000, b = 1000; long int c = a * b;" work?
A: You must manually cast one of the operands to (long).
3.16: Can I use ?: on the left-hand side of an assignment expression?
A: No.
Section 4. Pointers
4.2: What's wrong with "char *p; *p = malloc(10);"?
A: The pointer you declared is p, not *p.
4.3: Does *p++ increment p, or what it points to?
A: *p++ increments p. To increment the value pointed to by p, use (*p)++.
4.5: I want to use a char * pointer to step over some ints. Why doesn't "((int *)p)++;" work?
A: In C, a cast operator is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++.
4.8: I have a function which accepts, and is supposed to initialize, a pointer, but the pointer in the caller remains unchanged.
A: The called function probably altered only the passed copy of the pointer.
4.9: Can I use a void ** pointer as a parameter so that a function can accept a generic pointer by reference?
A: Not portably.
4.10: I have a function which accepts a pointer to an int. How can I pass a constant like 5 to it?
A: You will have to declare a temporary variable.
4.11: Does C even have "pass by reference"?
A: Not really, though it can be simulated.
4.12: I've seen different methods used for calling functions via pointers.
A: The extra parentheses and explicit * are now officially optional, although some older implementations require them.
Section 5. Null Pointers
5.1: What is this infamous null pointer, anyway?
A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object or function.
5.2: How do I get a null pointer in my programs?
A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable or expression of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic function calls) a constant 0 with an appropriate explicit cast is required.
5.3: Is the abbreviated pointer comparison "if(p)" to test for non- null pointers valid?
A: Yes. The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer.
5.4: What is NULL and how is it #defined?
A: NULL is simply a preprocessor macro, #defined as 0 (or ((void *)0)), which is used (as a stylistic convention, in preference to unadorned 0's) to generate null pointers.
5.5: How should NULL be defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer?
A: The same as on any other machine: as 0. (The compiler makes the translation, upon seeing a 0, not the preprocessor; see also question 5.4.)
5.6: If NULL were defined as "((char *)0)," wouldn't that make function calls which pass an uncast NULL work?
A: Not in general. The complication is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0.
5.9: If NULL and 0 are equivalent as null pointer constants, which should I use?
A: Either; the distinction is entirely stylistic.
5.10: But wouldn't it be better to use NULL, in case the value of NULL changes?
A: No. NULL is a constant zero, so a constant zero is equally sufficient.
5.12: I use the preprocessor macro "#define Nullptr(type) (type *)0" to help me build null pointers of the correct type.
A: This trick, though valid, does not buy much.
5.13: This is strange. NULL is guaranteed to be 0, but the null pointer is not?
A: A "null pointer" is a language concept whose particular internal value does not matter. A null pointer is requested in source code with the character "0". "NULL" is a preprocessor macro, which is always #defined as 0 (or ((void *)0)).
5.14: Why is there so much confusion surrounding null pointers?
A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) may seem to suggest that the value could change some day, or on some weird machine.
5.15: I'm confused. I just can't understand all this null pointer stuff.
A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls."
5.16: Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes?
A: Such a requirement would accomplish little.
5.17: Seriously, have any actual machines really used nonzero null pointers?
A: Machines manufactured by Prime, Honeywell-Bull, and CDC, as well as Symbolics Lisp Machines, have done so.
5.20: What does a run-time "null pointer assignment" error mean?
A: It means that you've written, via a null pointer, to an invalid location. (See also question 16.8.)
Section 6. Arrays and Pointers
6.1: I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn't it work?
A: The declaration extern char *a simply does not match the actual definition. Use extern char a[].
6.2: But I heard that char a[] was identical to char *a.
A: Not at all. Arrays are not pointers. A reference like x[3] generates different code depending on whether x is an array or a pointer.
6.3: So what is meant by the "equivalence of pointers and arrays" in C?
A: An lvalue of type array-of-T which appears in an expression decays into a pointer to its first element; the type of the resultant pointer is pointer-to-T. So for an array a and pointer p, you can say "p = a;" and then p[3] and a[3] will access the same element.
6.4: Why are array and pointer declarations interchangeable as function formal parameters?
A: It's supposed to be a convenience.
6.7: How can an array be an lvalue, if you can't assign to it?
A: An array is not a "modifiable lvalue."
6.8: What is the real difference between arrays and pointers?
A: Arrays automatically allocate space which is fixed in size and location; pointers are dynamic.
6.9: Someone explained to me that arrays were really just constant pointers.
A: An array name is "constant" in that it cannot be assigned to, but an array is *not* a pointer.
6.11: I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C?
A: Yes, array subscripting is commutative in C. The array subscripting operation a[e] is defined as being identical to *((a)+(e)).
6.12: What's the difference between array and &array?
A: The type.
6.13: How do I declare a pointer to an array?
A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead.
6.14: How can I set an array's size at run time?
A: It's straightforward to use malloc() and a pointer.
6.15: How can I declare local arrays of a size matching a passed-in array?
A: Until recently, you couldn't; array dimensions had to be compile- time constants. C9X will fix this.
6.16: How can I dynamically allocate a multidimensional array?
A: The traditional solution is to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples.
6.17: Can I simulate a non-0-based array with a pointer?
A: Not if the pointer points outside of the block of memory it is intended to access.
6.18: My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer.
A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer.
6.19: How do I write functions which accept two-dimensional arrays when the width is not known at compile time?
A: It's not always particularly easy.
6.20: How can I use statically- and dynamically-allocated multidimensional arrays interchangeably when passing them to functions?
A: There is no single perfect method, but see the full list for some ideas.
6.21: Why doesn't sizeof properly report the size of an array which is a parameter to a function?
A: The sizeof operator reports the size of the pointer parameter which the function actually receives.
No comments:
Post a Comment