C and C++ Questions and Answers

 

 Contents


1 C
1.1. C Programming Language Primer
1.2. How should I decide which integer type to use?
1.3. Why aren’t the sizes of the standard types precisely defined?
1.4. Since C does not define sizes exactly, I have been using typedefs like int16 and int32. I can then define these typedefs to be int, short, long, etc., depending on what machine I am using. That should solve everything, right?
1.5. What should the 64-bit type on new, 64-bit machines be?
1.6. What’s wrong with this declaration? char* p1, p2; I get errors when I try to use p2.
1.7. I am trying to declare a pointer and allocate some space for it, but it’s not working. What’s wrong with this code? char *p; *p = malloc(10);
1.8. What’s the best way to declare and define global variables?
1.9. How can I make a sort of “semiglobal” variable, that is, one that’s private to a few functions spread across a few source files?
1.10. Do all declarations for the same static function or variable have to include the storage class static?
1.11. What does extern mean in a function declaration?
1.12. What’s the auto keyword good for?
1.13. What’s the difference between using a typedef or a preprocessor macro for a user-defined type?
1.14. I cannot seem to declare a linked list successfully. I tried this declaration, but the compiler gave me error messages. typedef struct {char *item; NODEPTR next;} *NODEPTR; Can’t a structure in C contain a pointer to itself?
1.15. How can I define a pair of mutually referential structures? I tried typedef struct {int afield; BPTR bpointer;} *APTR; typedef struct {int bfield; APTR apointer;} *BPTR; but the compiler doesn’t know about BPTR when it is used in the first structure declaration.
1.16. What does “typedef int (*funcptr)();” mean?
1.17. Why can’t I use const values in initializers and array dimensions, like this?
1.18. How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters, or figure out what similarly complicated declarations mean?
1.19. How can I declare a function that returns a pointer to a function of its own type? I’m building a state machine with one function for each state, each of which returns a pointer to the function for the next state. But I can’t find a way to declare the functions - I seem to need a function returning a pointer to a function returning a pointer to a function returning a pointer to a function ..., ad infinitum.
1.20. Can I declare a local array (or parameter array) of a size matching a passed-in array or set by another parameter?
1.21. I have an extern array defined in one file and used in another: filel.c: int array[] = {1, 2, 3}; file2.c: extern int array[]; Why doesn’t sizeof work on array in file2.c?
1.22. Why is my compiler complaining about an invalid redeclaration of a function that I define and call only once?
1.23. How can I determine which identifiers are safe for me to use and which are reserved?
1.24. What can I safely assume about the initial values of variables that are not explicitly initialized? If global variables start out as “zero,” is that good enough for null pointers and floating-point zeroes?
1.25. Why is this code not compiling? f() { char a[] = “Hello, world!”; }
1.26. What is the difference between these initializations? char a[] = “string literal”; char *p = “string literal”; My program crashes if I try to assign a new value to p[i].
1.27. Is char a[] = “abc”; legal?
1.28. I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one?
1.29. What’s the difference between these two declarations? struct x1 { ... }; typedef struct { ... ) x2;
1.30. Why doesn’t this work? struct x { ... }; x thestruct;
1.31. Can a structure contain a pointer to itself?
1.32. What’s the best way of implementing opaque (abstract) data types in C?
1.33. I came across some code that declared a structure like this: struct name {int namelen; char namestr[1];}; and then did some tricky allocation to make the namestr array act as if it had several elements, with the number recorded by namelen. How does this work? Is it legal or portable?
1.34. Why can’t structures be compared using the built-in = = and : _ operators?
1.35. How are structure passing and returning implemented?
1.36. How can I pass constant values to functions that accept structure arguments? How can I create nameless, immediate, constant structure values?
1.37. How can I read/write structures from/to data files?
1.38. Why is my compiler leaving holes in structures, wasting space - and preventing “binary” I/O to external data files? Can I turn off the padding or otherwise control the alignment of structure fields?
1.39. Why does sizeof report a larger size than I expect for a structure type, as if there were padding at the end?
1.40. How can I determine the byte offset of a field within a structure?
1.41. How can I access structure fields by name at run time?
1.42. If an array name acts like a pointer to the base of an array, why isn’t the same thing true of a structure?
1.43. This program works correctly, but it dumps core after it finishes. Why?
1.44. What’s the difference between a structure and a union?
1.45. Is there a way to initialize unions?
1.46. Is there an automatic way to keep track of which field of a union is in use?
1.47. What is the difference between an enumeration and a set of preprocessor #defines?
1.48. Are enumerations portable?
1.49. Is there an easy way to print enumeration values symbolically?
1.50. What do these colons and numbers mean in some structure declarations? struct record { char *name; int refcount : 4; unsigned dirty : 1; };
1.51. Why do people use explicit masks and bit-twiddling code so much instead of declaring bitfields?
1.52. Why doesn’t this code work? a[i] = i++;
1.53. Under my compiler, this code prints 49: int i = 7; printf(“%d\n”, i++ * i++); Regardless of the order of evaluation, shouldn’t it print 56?
1.54. I’ve experimented with this code on several compilers: int i = 3; i = i++; Some gave i the value 3, some gave 4, but one gave 7. I know that the behavior is undefined, but how could it give 7?
1.55. Can I use explicit parentheses to force the order of evaluation I want and control these side effects? Even if I do not, doesn’t precedence dictate it?
1.56. But what about the && and || operators? I see code like “while((c = getchar()) != EOF && c != ‘\n’)”.
1.57. Is it safe to assume that the right-hand side of the && and || operators won’t be evaluated if the left-hand side determines the outcome?
1.58. Why did printf(“%d %d”, f1(), f2()); call f2 first? I thought that the comma operator guaranteed left-to-right evaluation.
1.59. How can I understand complex expressions and avoid writing undefined ones? What’s a “sequence point”?
1.60. So if I write a[i] = i++; and I do not care which cell of a[] gets written to, the code is fine, and i gets incremented by 1, right?
1.61. How can I avoid these undefined evaluation-order difficulties if I do not feel like learning the complicated rules?
1.62. If I’m not using the value of the expression, should I use i++ or ++i to increment a variable?
1.63. I need to assign a complicated expression to one of two variables, depending on a condition. Can I use code like this? ((condition) ? a : b) = complicated expression;
1.64. I have some code containing expressions like a ? b = c : d Some compilers are accepting it but some are not. Why?
1.65. What does the warning “semantics of ‘>’ change in ANSI C” mean?
1.66. What’s the difference between the “unsigned preserving” and “value preserving” rules?
1.67. What are pointers really good for, anyway?
1.68. I’m trying to declare a pointer and allocate some space for it, but it’s not working. What’s wrong with this code? char *p; *p = malloc(10);
1.69. What does *p++ increment: p or what it points to?
1.70. I am trying to use pointers to manipulate an array of ints. What’s wrong with this code? int array[5], i, *ip; for(i = 0; i < 5; i++) array[i] = i; ip = array; printf(“%d\n”, *(ip + 3 * sizeof(int))); I expected the last line to print 3, but it printed garbage.
1.71. I have a char * pointer that happens to point to some ints, and I want to step it over them. Why doesn’t this code work? ((int *)p)++;
1.72. I have a function that accepts, and is supposed to initialize, a pointer: void f(ip) int *ip; static int dummy = 5; ip = &dummy; But when I call it like this: int *ip; f(ip); the pointer in the caller remains unchanged.
1.73. If I want to write a function that takes a generic pointer as an argument and I want to simulate passing it by reference, can I give the formal parameter type void ** and do something like this? void f(void **); double *dp; f((void **)&dp);
1.74. I have a function extern int f(int *); that accepts a pointer to an int. How can I pass a constant by reference? A call like f(&5); doesn’t seem to work.
1.75. Does C even have “pass by reference”?
1.76. I’ve seen different methods used for calling functions via pointers. What’s the story?
1.77. What’s the total generic pointer type? My compiler complained when I tried to stuff function pointers into a void *.
1.78. How are integers converted to and from pointers? Can I temporarily stuff an integer into a pointer, or vice versa?
1.79. What is this infamous null pointer, anyway?
1.80. How do I get a null pointer in my programs?
1.81. Is the abbreviated pointer comparison “if (p)” to test for non-null pointers valid? What if the internal representation for null pointers is nonzero?
1.82. What is NULL and how is it defined?
1.83. How should NULL be defined on a machine that uses a nonzero bit pattern as the internal representation of a null pointer?
1.84. If NULL were defined as follows: #define NULL ((char *)0) wouldn’t that make function calls that pass an uncast NULL work?
1.85. My vendor provides header files that define NULL as 0L. Why?
1.86. Is NULL valid for pointers to functions?
1.87. If NULL and 0 are equivalent as null pointer constants, which should I use?
1.88. But wouldn’t it be better to use NULL rather than 0 in case the value of NULL changes, perhaps on a machine with nonzero internal null pointers?
1.89. I once used a compiler that wouldn’t work unless NULL was used.
1.90. I use the preprocessor macro #define Nullptr(type) (type *)0 to help me build null pointers of the correct type.
1.91. This is strange: NULL is guaranteed to be 0, but the null pointer is not?
1.92. Why is there so much confusion surrounding null pointers? Why do these questions come up so often?
1.93. Is there an easier way to understand all this null pointer stuff?
1.94. Given all the confusion surrounding null pointers, wouldn’t it be easier simply to require them to be represented internally by zeroes?
1.95. Is a run-time integral value of 0, cast to a pointer, guaranteed to be a null pointer?
1.96. How can I access an interrupt vector located at the machine’s location 0? If I set a pointer to 0, the compiler might translate it to a nonzero internal null pointer value.
1.97. What does a run-time “null pointer assignment” error mean? How do I track it down?
1.98. I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn’t it work?
1.99. Is char a[] identical to char *a?
1.100. What is meant by the “equivalence of pointers and arrays” in C?
1.101. If they're so different, why are array and pointer declarations interchangeable as function formal parameters?
1.102. Why can’t I do something like this? extern char *getpass(); char str[10]; str = getpass(“Enter password: ”);
1.103. If I can’t assign to arrays, then how can this code work?
1.104. How can an array be an lvalue if I can’t assign to it?
1.105. What is the difference between arrays and pointers?
1.106. Someone explained to me that arrays are really just constant pointers. Is this accurate?
1.107. Is a pointer a kind of array, or is an array a kind of pointer?
1.108. I came across some “joke” code containing the “expression” 5[“abcdef”] . How can this be legal C?
1.109. Since array references decay into pointers, what’s the difference - if array is an array - between array and &array?
1.110. How do I declare a pointer to an array?
1.111. How can I set an array’s size at run time? How can I avoid fixed-sized arrays?
1.112. How can I declare local arrays of a size matching a passed-in array?
1.113. How can I dynamically allocate a multidimensional array?
1.114. If I write int realarray[10]; int *array = &realarray[-1]; I can treat array as if it were a 1-based array. Is this legal?
1.115. Why does the compiler complain when I pass a two-dimensional array to a function expecting a pointer to a pointer?
1.116. How do I write functions that accept two-dimensional arrays when the “width” is not known at compile time?
1.117. How can I use statically and dynamically allocated multidimensional arrays interchangeably when passing them to functions?
1.118. Why doesn’t sizeof properly report the size of an array when the array is a parameter to a function? I have this test function and it prints 4, not 10: f(char a[10]) {int i = sizeof(a); printf(“%d\n”, i);}
1.119. How can I determine how many elements are in an array, when sizeof yields the size in bytes?
1.120. Why doesn’t this fragment work? char *answer; printf(“Type something:\n”); gets(answer); printf(“You typed ”%s“\n”, answer);
1.121. Why can’t I get strcat to work? I tried char *s1 = “Hello, ”; char *s2 = “world!”; char *s3 = strcat(s1, s2); but I got strange results.
1.122. How am I supposed to know to allocate things as the documentation for strcat says that it takes two char * pointers as arguments?
1.123. I am reading lines from a file into an array, with this code: char linebuf[80]; char *lines[100]; int i; for(i = 0; i < 100; i++) {char *p = fgets(linebuf, 80, fp); if(p == NULL) break; lines[i] = p;} Why do all the lines end up containing copies of the last line?
1.124. I have a function that is supposed to return a string, but when the function returns to its caller, the returned string is garbage. Why?
1.125. Why am I getting “warning: assignment of pointer from integer lacks a cast” for calls to malloc?
1.126. Why does some code carefully cast the values returned by malloc to the pointer type being allocated?
1.127. I see code like this: char *p = malloc(strlen(s) + 1); strcpy(p, s); Shouldn’t that be malloc((strien(s) + 1) * sizeof(char))?
1.128. I’ve heard that some operating systems do not allocate memory obtained via malloc until the program tries to use it. Is this legal?
1.129. Why is malloc returning crazy pointer values? I have included the declaration extern void *malloc(); before I call it.
1.130. I am allocating a large array for some numeric work, using the line double *array = malloc(256 * 256 * sizeof(double)); Although malloc isn’t returning null, the program is acting strangely, as if it’s overwriting memory or malloc isn’t allocating as much as I asked for. Why?
1.131. My application depends heavily on dynamic allocation of nodes for data structures, and malloc/free overhead is becoming a bottleneck. What can I do?
1.132. My program is crashing, apparently somewhere down inside malloc, although I can’t see anything wrong with it. What’s wrong?
1.133. Can dynamically allocated memory be used after freeing it?
1.134. Why isn’t a pointer null after calling free? How unsafe is it to use (assign, compare) a pointer value after it’s been freed?
1.135. When I call malloc to allocate memory for a local pointer, do I have to explicitly free it?
1.136. I am allocating structures containing pointers to other dynamically allocated objects. When I free a structure, do I have to free each subsidiary pointer first?
1.137. Must I free allocated memory before the program exits?
1.138. I have a program that allocates and later frees a lot of memory, but memory usage doesn’t seem to go back down. Why?
1.139. How does free () know how many bytes to free?
1.140. Can I query the malloc package to find out how big an allocated block is?
1.141. Why doesn’t sizeof tell me the size of the block of memory pointed to by a pointer?
1.142. Having dynamically allocated an array, can I change its size?
1.143. Is it legal to pass a null pointer as the first argument to realloc()? Why would you want to?
1.144. What’s the difference between calloc and malloc? Which should I use? Is it safe to take advantage of calloc’s zero-filling? Does free work on memory allocated with calloc, or do you need a cfree?
1.145. What is alloca and why is its use discouraged?
1.146. Why doesn’t strcat (string, '!'); work?
1.147. I am checking a string to see whether it matches a particular value. Why isn’t this code working? char *string; … if (string == “value”) { /* string matches “value” */ … }
1.148. If I can say char a[] = “Hello, world!”; why can’t I say char a[14]; a = “Hello, world!”;
1.149. How can I get the numeric value (i.e., ASCII or other character set code) corresponding to a character, or vice versa?
1.150. I’m reading strings typed by the user into an array and then printing them out later. When the user types a sequence like \n, why isn’t it being handled properly?
1.151. I just noticed that sizeof ('a') is 2, not 1 (i.e., not sizeof(char)). Is something wrong with my compiler?
1.152. I’m starting to think about multinational character sets. Should I worry about the implications of making sizeof(char) be 2 so that 16-bit character sets can be represented?
1.153. What is the right type to use for Boolean values in C? Why isn’t it a standard type? Should I use #defines or enums for the true and false values?
1.154. Isn’t defining TRUE to be 1 dangerous, since any nonzero value is considered “true” in C? What if a built-in logical or a relational operator “returns” something other than 1?
1.155. Is if(p), where p is a pointer, a valid conditional?
1.156. Should I use symbolic names, such as TRUE and FALSE, for Boolean constants or use plain 1 and 0?
1.157. I am trying to define a few simple little function-like macros, such as #define square(x) x*x but they are not always working. Why?
1.158. Is it okay to use some preprocessor macros like these using which I can write C code that looks more like Pascal?
1.159. How can I write a generic macro to swap two values?
1.160. What’s the best way to write a multistatement macro?
1.161. I’m splitting up a program into multiple source files for the first time. What should I put in .c files and what should I put in .h files?
1.162. Is it acceptable for one header file to include another?
1.163. Where are header (“#include”) files searched for?
1.164. Why am I getting strange syntax errors on the very first declaration in a file?
1.165. I’m using header files that accompany two different third-party libraries, and they are “helpfully” defining common macros, such as TRUE, FALSE, Min(), and Max(), but the definitions clash with each other and with definitions I’d already established in my own header files. What can I do?
1.166. I seem to be missing the system header file . Where can I get a copy?
1.167. How can I construct preprocessor #if expressions that compare strings?
1.168. Does the sizeof operator work in preprocessor #if directives?
1.169. Can I use #ifdef in a #define line to define something in two different ways, like this?
1.170. Is there anything like an #ifdef for typedefs?
1.171. How can I use a preprocessor #if expression to tell whether a machine’s byte order is big-endian or little-endian?
1.172. How can I list all of the predefined macros?
1.173. I have some old code that tries to construct identifiers with a macro like #define Paste(a, b) a/**/b but it’s not working any more. Why?
1.174. I have an old macro #define CTRL(c) ('c & 037) that doesn’t seem to work any more. Why?
1.175. How can I do this really tricky preprocessing?
1.176. How can I write a macro that takes a variable number of arguments or use the preprocessor to “turn off” a function call with a variable number of arguments?
1.177. How can I include expansions of the __FILE__ and __LINE__ macros in a general-purpose debugging macro?
1.178. Why does my ANSI compiler complain about a mismatch when it sees extern int func(float); int func(x) float x; {…}
1.179. Is it possible to mix old-style and new-style function syntax?
1.180. Why does the declaration extern f(struct x *p); give me an obscure warning message about “struct x introduced in prototype scope” or “struct x declared inside parameter list”?
1.181. Why can’t I use const values in initializers and array dimensions, as in: const int n = 5; int a[n];
1.182. What’s the difference between const char *p, char const *p, and char * const p?
1.183. Why can’t I pass a char * * to a function that expects a const char **?
1.184. I’ve got the declarations typedef char *charp; const charp p; Why is p turning out const instead of the characters pointed to?
1.185. Can I declare main as void to shut off these warnings about main not returning a value?
1.186. What about main’s third argument, envp?
1.187. I believe that declaring void main() can’t fail, since I’m calling exit instead of returning. Anyway, my operating system ignores a program’s exit/return status.
1.188. Is exit(status) truly equivalent to returning the same status from main?
1.189. I’m trying to use the ANSI “stringizing” preprocessing operator ‘#’ to insert the value of a symbolic constant into a message, but it keeps stringizing the macro’s name rather than its value. Why?
1.190. Why am I getting strange syntax errors inside lines I’ve used #ifdef to disable?
1.191. What is the #pragma directive and what is it good for?
1.192. What does “#pragma once” mean?
1.193. Is char a[3] = “abc”; legal? What does it mean?
1.194. Why can’t I perform arithmetic on a void * pointer?
1.195. What is the difference between memcpy and memmove?
1.196. What should malloc(0) do: return a null pointer or a pointer to 0 bytes?
1.197. People seem to make a point of distinguishing among implementation-defined, unspecified, and undefined behavior. What do these terms mean?
1.198. I’m appalled that the ANSI standard leaves so many issues undefined. Isn’t a standard’s whole job to standardize these things?
1.199. People keep saying that the behavior of i = i++ is undefined, but I just tried it on an ANSI-conforming compiler and got the results I expected. Is it really undefined?
1.200. What’s wrong with this code? char c; while((c = getchar()) != EOF) ...
1.201. Why does the simple line-copying loop while(!feof(infp)) { fgets(buf, MAXLINE, infp); fputs(buf, outfp); } copy the last line twice?
1.202. My program’s prompts and intermediate output do not always show up on the screen, especially when I pipe the output through another program. Why not?
1.203. How can I read one character at a time without waiting for the Return key?
1.204. How can I print a '%' character in a printf format string? I tried \%, but it didn’t work.
1.205. Why doesn’t this code work?long int n = 123456; printf(“%d\n”, n);
1.206. Someone told me that it is wrong to use %lf with printf. How can printf use %f for type double if scanf requires %lf?
1.207. How can I implement a variable field width with printf? That is, instead of something like %8d, I want the width to be specified at run time.
1.208. Why doesn’t the call scanf (“%d”, i) work?
1.209. Why doesn’t this code work? double d; scarf(“%f”, &d);
1.210. Why doesn’t this code work? short int s; scanf(“%d”, &s);
1.211. How can I specify a variable width in a scanf format string?
1.212. How can I read data from data files with particular formats? How can I read 10 floats without having to use a scanf format mentioning 9sf 10 times? How can I read an arbitrary number of fields from a line into an array?
1.213. When I read numbers from the keyboard with scanf and a “%d\n” format, like this: int n; scanf(“%d\n”, &n); printf(“you typed %d\n”, n); it seems to hang until I type one extra line of input. Why?
1.214. I’m reading a number with scanf and %d and then a string with gets():
1.215. I figured I could use scanf more safely if I checked its return value to make sure that the user typed the numeric values I expect:
1.216. Why does everyone say not to use scanf? What should I use instead?
1.217. How can I tell how much destination buffer space I’ll need for an arbitrary sprintf call? How can I avoid overflowing the destination buffer with sprintf?
1.218. What’s the deal on sprintf’s return value? Is it an int or a char *?
1.219. Why does everyone say not to use gets()?
1.220. I thought I’d check errno after a long string of printf calls to see whether any of them had failed:
1.221. What’s the difference between fgetpos/fsetpos and ftell/fseek? What are fgetpos and fsetpos good for?
1.222. How can I flush pending input so that a user’s typeahead isn’t read at the next prompt? Will fflush(stdin) work?
1.223. I wrote this function, which opens a file: myfopen(char *filename, FILE *fp) {fp = fopen(filename, “r”); But when I call it like this: FILE *infp; myfopen(“filename.dat”, infp); the infp variable in the caller doesn’t get set properly. Why not?
1.224. I can’t even get a simple f open call to work! What’s wrong with this call? FILE *fp = fopen(filename, 'r');
1.225. Why can’t I open a file by its explicit path? This call is failing: fopen(“c:\newdir\file.dat”, “r”)
1.226. I’m trying to update a file in place by using fopen mode “r+”, reading a certain string, and writing back a modified string, but it’s not working. Why not?
1.227. How can I redirect stdin or stdout to a file from within a program?
1.228. Once I’ve used freopen, how can I get the original stdout (or stdin) back?
1.229. How can I tell whether standard input or output is redirected, i.e., whether “<” or “>” was used on the invocation command line?
1.230. I’m trying to write a program like “more.” How can I get back to the interactive keyboard if stdin is redirected?
1.231. I want to read and write numbers directly between files and memory a byte at a time, not as formatted characters the way fprintf and fscanf do. How can I do this?
1.232. How can I read a binary data file properly? I’m occasionally seeing 0x0a and 0x0d values getting garbled, and it seems to hit EOF prematurely if the data contains the value 0x1a.
1.233. I’m writing a “filter” for binary files, but stdin and stdout are preopened as text streams. How can I change their mode to binary?
1.234. What’s the difference between text and binary I/O?
1.235. How can I write code to conform to these old, binary data file formats?
1.236. How can I convert numbers to strings (the opposite of atoi)? Is there an itoa function?
1.237. Why does strncpy not always place a '\0' terminator in the destination string?
1.238. Does C have anything like the “substr” (extract substring) routine present in other languages?
1.239. How do I convert a string to all uppercase or all lowercase?
1.240. How can I split up a string into whitespace-separated fields? How can I duplicate the process by which main() is handed argc and argv?
1.241. Where can I get some code to do regular expression and wildcard matching?
1.242. I’m trying to sort an array of strings with qsort, using strcmp as the comparison function, but it’s not working. Why not?
1.243. I’m trying to sort an array of structures with qsort. My comparison function takes pointers to structures, but the compiler complains that the function is of the wrong type for qsort. How can I cast the function pointer to shut off the warning?
1.244. How can I sort a linked list?
1.245. How can I sort more data than will fit in memory?
1.246. How can I get the current date or time of day in a C program?
1.247. I know that the library function locaitime will convert a time_t into a broken-down struct tm and that ctime will convert a time_t to a printable string. How can I perform the inverse operations of converting a struct tm or a string into a time_t?
1.248. How can I add n days to a date? How can I find the difference between two dates?
1.249. How can I generate random numbers?
1.250. How can I get random integers in a certain range?
1.251. Each time I run my program, I get the same sequence of numbers back from rand. Why?
1.252. I need a random true/false value, so I’m just taking rand() % 2, but it’s alternating 0, 1, 0, 1, 0.... Why?
1.253. How can I return a sequence of random numbers that do not repeat at all?
1.254. How can I generate random numbers with a normal, or Gaussian, distribution?
1.255. What is a function drand48?
1.256. I keep getting errors due to library functions being undefined, even though I’m including all the right header files.
1.257. I’m still getting errors due to library functions being undefined, even though I’m explicitly requesting the right libraries while linking.
1.258. Why is my simple program, which hardly does more than print “Hello, world!” in a window, compiling to such a huge executable (several hundred K)? Should I include fewer header files?
1.259. What does it mean when the linker says that _end is undefined?
1.260. When I set a float variable to, say, 3.1, why is printf printing it as 3.0999999?
1.261. I’m trying to take some square roots, and I’ve simplified the code down to main() printf('%f\n”, sqrt(144.)); } but I’m still getting crazy numbers. Why?
1.262. I’m trying to do some simple trig, and I am including , but the linker keeps complaining that functions such as sin and cos are undefined. Why?
1.263. My floating-point calculations are acting strangely and giving me different answers on different machines. Why?
1.264. What’s a good way to check for “close enough” floating-point equality?
1.265. How do I round numbers?
1.266. Why doesn’t C have an exponentiation operator?
1.267. The predefined constant M_PI seems to be missing from my machine’s copy of . Shouldn’t it be there?
1.268. How do I set variables to or test for IEEE NaN (“Not a Number”) and other special values?
1.269. What’s a good way to implement complex numbers in C?
1.270. I’m having trouble with a Turbo C program that crashes and says something like “floating point formats not linked.” What am I missing?
1.271. I heard that you have to include before calling printf. Why?
1.272. How can %f be used for both float and double arguments in print f? Aren’t they different types?
1.273. I had a frustrating problem that turned out to be caused by the line
1.274. How can I write a function that takes a variable number of arguments?
1.275. How can I write a function that, like printf, takes a format string and a variable number of arguments, and passes them to printf to do most of the work?
1.276. How can I write a function analogous to scanf, i.e., that accepts similar arguments, and calls scanf to do most of the work?
1.277. I have a pre-ANSI compiler, without . What can I do?
1.278. How can I discover how many arguments were used to call a function?
1.279. My compiler isn’t letting me declare a function
1.280. I have a varargs function that accepts a float parameter. Why isn’t the call va_arg(argp, float) extracting it correctly?
1.281. I can’t get va_arg to pull in an argument of type pointer to function. Why not?
1.282. How can I write a function that takes a variable number of arguments and passes them to another function (which takes a variable number of arguments) ?
1.283. How can I call a function with an argument list built up at run time?
1.284. Why is this loop always executing once?
1.285. This program crashes before it even runs! (When single stepping with a debugger, it dies before the first statement in main.) Why?
1.286. I have a program that seems to run correctly, but it crashes as it’s exiting, after the last statement in main () . What could be causing this?
1.287. This program runs perfectly on one machine, but I get weird results on another. Stranger still, adding or removing debugging printouts changes the symptoms. What’s wrong?
1.288. Why does this code crash?
1.289. I’ve got some code that’s trying to unpack external structures, but it’s crashing with a message about an “unaligned access.” What does this mean? The code looks like this:
1.290. What do “segmentation violation” and “bus error” mean? What’s a “core dump”?
1.291. What’s the best style for code layout in C?
1.292. How should functions be apportioned among source files?
1.293. Here’s a neat trick for checking whether two strings are equal: if(!stranp(s1, s2)) Is this good style?
1.294. Why do some people write if (0 == x) instead of if (x == 0) ?
1.295. I came across some code that puts a (void) cast before each call to printf. Why?
1.296. What is “Hungarian notation”? Is it worthwhile?
1.297. Some people say that goto statements are evil and that I should never use them. Isn’t that a bit extreme?
1.298. People always say that good style is important, but when they go out of their way to use clear techniques and make their programs readable, they seem to end up with less efficient programs. Since efficiency is so important, isn’t it necessary to sacrifice some style and readability?
1.299. I just typed in this program, and it’s acting strangely. What can be wrong with it?
1.300. How can I shut off the “warning: possible pointer alignment problem” message that lint gives me for each call to malloc?
1.301. How can I read a single character from the keyboard without waiting for the Return key? How can I stop characters from being echoed on the screen as they're typed?
1.302. How can I find out whether characters are available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if no characters are available?
1.303. How can I display a percentage-done indication that updates itself in place or show one of those “twirling baton” progress indicators?
1.304. How can I clear the screen? How can I print things in inverse video? How can I move the cursor to a specific x, y position?
1.305. How do I read the arrow keys? What about function keys?
1.306. How can I do serial (“comm”) port I/O?
1.307. How can I direct output to the printer?
1.308. How do I send escape sequences to control a terminal or other device?
1.309. How can I check whether a file exists? I want to warn the user if a requested input file is missing.
1.310. How can I find out the size of a file prior to reading it in?
1.311. How can a file be shortened in place without completely clearing or rewriting it?
1.312. How can I insert or delete a line (or record) in the middle of a file?
1.313. How can I recover the file name given an open stream or file descriptor?
1.314. How can I delete a file?
1.315. Why can’t I open a file by its explicit path? This call is failing:
1.316. I’m getting an error: “Too many open files.” How can I increase the allowable number of simultaneously open files?
1.317. How can I find out how much free space is available on disk?
1.318. How can I read a directory in a C program?
1.319. How do I create a directory? How do I remove a directory (and its contents)?
1.320. How can I find out how much memory is available?
1.321. How can I access memory (a memory-mapped device or graphics memory) located at a certain address? How can I do PEEK and POKE in C?
1.322. How can I invoke another program (a standalone executable or an operating system command) from within a C program?
1.323. How can I call system when parameters (filenames, etc.) of the executed command aren’t known until run time?
1.324. How can I invoke another program or command and trap its output?
1.325. How can my program discover the complete pathname to the executable from which it was invoked?
1.326. How can a process change an environment variable in its caller?
1.327. How can I read in an object file and jump to functions in it?
1.328. How can I implement a delay or time a user’s response with sub-second resolution?
1.329. How can I trap or ignore keyboard interrupts like control-C?
1.330. How can I handle floating-point exceptions gracefully?
1.331. How can I return multiple values from a function?
1.332. What’s a good data structure to use for storing lines of text? I started to use fixed-size arrays of arrays of char, but they're too restrictive.
1.333. How can I open files mentioned on the command line and parse option flags?
1.334. What’s the right way to use errno?
1.335. How can I write data files that can be read on other machines with different word size, byte order, or floating-point formats?
1.336. If I have a char * variable pointing to the name of a function, how can I call that function? Code like
1.337. How can I manipulate individual bits?
1.338. How can I implement sets or arrays of bits?
1.339. How can I determine whether a machine’s byte order is bigendian or little-endian?
1.340. How can I convert integers to binary or hexadecimal?
1.341. Can I use base-2 constants (something like Ob101010)? Is there a printf format for binary?
1.342. What is the most efficient way to count the number of bits that are set in a value?
1.343. How can I make my code more efficient?
1.344. Are pointers really faster than arrays? How much do function calls slow things down? Is ++i faster than i = i + 1?
1.345. Is it worthwhile to replace multiplications and divisions with shift operators?
1.346. Which is more efficient: a switch statement or an if/else chain?
1.347. Is there a way to switch on strings?
1.348. Is there a way to have nonconstant case labels (i.e., ranges or arbitrary expressions)?
1.349. Are the outer parentheses in return statements really optional?
1.350. Why do not C comments nest? How am I supposed to comment out code containing comments? Are comments legal inside quoted strings?
1.351. Why isn’t C’s set of operators more complete? A few operators, such as A#. & and ->=, seem to be missing.
1.352. If the assignment operator were : _, wouldn’t it then be harder to accidentally write things like if (a = b) ?
1.353. Why doesn’t C have nested functions?
1.354. How can I call C++ functions from C? (And vice versa?)
1.355. Is C++ a superset of C? What are the differences between C and C++? Can I use a C++ compiler to compile C code?
1.356. I need a sort of an “approximate” strcmp routine for comparing two strings for close, but not necessarily exact, equality. What’s a good way to do that?
1.357. What is hashing?
1.358. How can I find the day of the week given the date?
1.359. Will 2000 be a leap year? Is (year % 4 == 0) an accurate test for leap years?
1.360. Why can tm_sec in the tm structure range from 0 to 61, suggesting that there can be 62 seconds in a minute?
1.361. How do you write a program that produces its own source code as its output?
1.362. Where does the name “C” come from, anyway?
2 C++
2.1. What is the difference between C and C++?
2.2. What are the differences between C++ and Java?
2.3. How does function declaration differ in C++ versus Java?
2.4. Describe memory organization of an executable program.
2.5. What is the difference between the preprocessor directive #include “file.h” and #include ?
2.6. Explain the different storage classes in C.
2.7. What is a heap? What are the two main applications of heaps?
2.8. Why are heaps used to implement priority queues?
2.9. What is the difference between the Heap and the Stack? Where in memory are these located relative to the executing program?
2.10. How does function declaration differ from function definition?
2.11. Is there anything you can do in C++ that you cannot do in C?
2.12. What is the difference between a class and a struct in C++?
2.13. What are the three main characteristics of object orientation?
2.14. What is identity?
2.15. What is abstraction?
2.16. What is encapsulation?
2.17. What is inheritance?
2.18. What is multiple inheritance?
2.19. What is hierarchical inheritance?
2.20. What is generalization?
2.21. What is polymorphism?
2.22. How do you implement polymorphism?
2.23. What would you say if you saw “delete this” while reviewing your peer’s code? What is your reaction to this line of code? delete this;
2.24. What are friendly methods in C++? What is the impact of friend functions on performance?
2.25. Class B is derived from class A. Function f is A’s friend. Is f B’s friend as well?
2.26. What are the access privileges in C++? What is the default access level?
2.27. What is the difference between private, protected, and public members of a class?
2.28. What is the difference between non-virtual and virtual functions?
2.29. What do you mean by virtual methods in C++? What are virtual functions in C++?
2.30. How do you make a virtual function call?
2.31. Why should you never call virtual functions from a constructor?
2.32. What is a pure virtual function?
2.33. What is an abstract base class?
2.34. What is the difference between MyClass p; and MyClass p();?
2.35. Why were the templates introduced? Give examples of templates.
2.36. What is a static member of a class?
2.37. What feature of C++ would you use if you wanted to design a member function that guarantees to leave “this” object unchanged?
2.38. What is function’s signature?
2.39. What is operator overloading?
2.40. What is the difference between function overloading and function overriding?
2.41. When implementing a class, what methods sould always be overridden and why?
2.42. Can you overload a function based only on whether a parameter is a value or a reference?
2.43. Can derived class override some but not all of a set of overloaded virtual member functions inherited from the base class?
2.44. What is the difference between assignment and initialization in C++?
2.45. Does compiler guarantee that initializers will be executed in the same order as they appear on the initialization list?
2.46. Why use an initialization list in a constructor?
2.47. Why do C++ compilers need name mangling?
2.48. What does extern “C” int func(int *, Foo) accomplish?
2.49. How do you link a C++ program to C functions?
2.50. What are pointers?
2.51. What is a reference?
2.52. What is the difference between a pointer and a reference?
2.53. What is dereferencing a pointer?
2.54. Consider the following C++ function prototypes for a function, foo, which takes an object of class Fruit as an argument. void foo(Fruit bar); // Prototype 1 void foo(Fruit* bar); // Prototype 2 void foo(Fruit& bar); // Prototype 3 void foo(const Fruit* bar); // Prototype 4 void foo(Fruit* const bar); // Prototype void foo(Fruit*& bar); // Prototype 5 For each prototype, discuss how the argument will be passed and what the implications would be for a function implemented using that method of argument passing.
2.55. What is the difference between const char *myPointer and char *const myPointer? What is the difference between a const pointer and a pointer to a const?
2.56. What is a dangling pointer?
2.57. What dire consequences could result from deferencing a dangling pointer?
2.58. How can these dire consequences be avoided?
2.59. What is the only thing that you should ever do with the NULL pointer?
2.60. What does it mean to say that an array is really a constant pointer?
2.61. How do you declare an array of strings?
2.62. Illustrate the use of * and & for pointers in C.
2.63. Is there any problem with the following? char *a = NULL; char& p = *a;
2.64. What is a pointer to a function? What are the common uses of function pointers?
2.65. How can you access the static member of a class?
2.66. Explain the scope resolution operator.
2.67. How are prefix and postfix versions of operator++() differentiated?
2.68. What functions does C++ silently write and call?
2.69. What is the difference between new/delete and malloc/free?
2.70. What is the difference between delete and delete[]?
2.71. Name two cases where you must use initialization list as opposed to assignment in constructors.
2.72. Suppose that objects A, B, and C are instances of class MyClass (MyClass A, B, C;). How should you design an assignment operator so that the “A=B=C;” statement would be allowed by a compiler but “(A=B)=C;” would not be allowed by a compiler?
2.73. What issue do auto_ptr objects address?
2.74. What is the difference between an ‘exception’ and an ‘error’?
2.75. What happens when a function throws an exception that was not specified by an exception specification for this function?
2.76. What do you mean by Stack unwinding?
2.77. Explain TRY and CATCH exception handling in C++. Why is this type of exception handling useful?
2.78. How does throwing and catching exceptions differ from using setjmp and longjmp?
2.79. Why should you prefer throw/catch mechanism to setjmp/longjmp?
2.80. Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?
2.81. What is a constructor? What name must a constructor have? How many constructors can a class have?
2.82. What is a default constructor?
2.83. When you must have a default constructor?
2.84. Are the “default constructor” and “constructor with default parameter” same?
2.85. When are copy constructors called?
2.86. Why do you have to provide your own copy constructor and assignment operator for classes with dynamically allocated memory?
2.87. What is the difference between shallow versus deep copies?
2.88. Does a class provide default copy constructor?
2.89. What does a default copy constructor do?
2.90. When does a programmer need to implement his own copy constructor?
2.91. Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?
2.92. What is the return parameter of a constructor and why?
2.93. What is an explicit constructor?
2.94. What is a conversion constructor?
2.95. What is the difference between a copy constructor and an overloaded assignment operator?
2.96. What is a destructor? What name must a destructor have? How many destructors can a class have?
2.97. When and in what condition a destructor is called?
2.98. What is a virtual destructor?
2.99. How do you know that your class needs a virtual destructor?
2.100. Does a destructor have some function parameter or return parameter?
2.101. In C++, what is the usefulness of virtual destructors?
2.102. Can a program have a virtual constructor?
2.103. Explain the ISA and HASA class relationships. How would you implement each in a class design?
2.104. What is the difference between Class and Interface? Give an example where only Interface is used.
2.105. When to use an interface and when to use an abstract class?
2.106. What is a Vector class?
2.107. What is a memory leak? How do you prevent memory leaks?
2.108. Describe the difference between arguments and parameters.
2.109. What are the differences between passing a parameter by value and passing by reference?
2.110. What are the differences between passing a parameter by reference and by constant reference?
2.111. What are typedefs? What are the advantages of using them?
2.112. How does an enum statement differ from a typedef statement?
2.113. When a multi-dimensional array is passed to a function, why does C++ require all but the first dimension to be specified in the parameter list?
2.114. What is the difference between C string vs. C++ string?
2.115. What is a stream?
2.116. What is the difference between sequential access and direct access?
2.117. Explain Bubble sort.
2.118. How many ways are there to initialize an int with a constant?
2.119. When should you use multiple inheritance?
2.120. How can I make sure at most one instance of my class is ever created?
2.121. When is a template a better solution than a base class?
2.122. What is a mutable member?
2.123. What is STL?
2.124. What are different types of iterators in STL?
2.125. Describe run-time type identification.
2.126. What problem does the namespace feature solve?
2.127. Are there any new intrinsic (built-in) data types?
2.128. What do you mean by multiple inheritance in C++?
2.129. What are the advantages and disadvantages of using macros?
2.130. What are inline functions? What are the two ways of declaring inline functions?
2.131. What are the advantages and disadvantages of using inline functions?
2.132. Why not inline everything?
2.133. Is inline functions always fast?
2.134. Class B is a subclass of Class A. Class C is a subclass of Class B. If a method in Class A is made private in Class B, can this method be accessed in Class C?
2.135. What does a PASCAL function type in a C function declaration mean?
2.136. In C++, what is the difference between allocating memory on the heap vs. allocating it on the stack? (new vs. normal declaration) Which would be better for an array of two elements? What if you have 100 arrays of 2 elements? Which is better for an array of 2000 elements?
2.137. What is the difference between stack and heap? Which one is faster?
2.138. Describe the data structures of a double-linked list. How do you insert a record between two others?
2.139. What is the difference between a WHILE loop and FOR loop construct?
2.140. Describe GCC
2.141. If your code is crashing, what would you look for first?
2.142. How is the memory aligned in case of a Union?
2.143. To Virtual Or Not To Virtual?
2.144. What are the differences between Structs and Unions?
2.145. How are the arguments to scanf evaluated?
2.146. How do you do efficient array copying?
2.147. What are the phases of Object construction?
2.148. Dynamic Memory Allocations and Thread Safety
2.149. Why virtual member functions should not be private?
2.150. What is an Abstraction?
2.151. What is multiple inheritance?
2.152. What are the advantages and disadvantages of multiple inheritance?
2.153. What is encapsulation?
2.154. What is inheritance?
2.155. What is Polymorphism?
2.156. What is constructor or ctor?
2.157. What is destructor?
2.158. What is default constructor?
2.159. What is copy constructor?
2.160. When is copy constructors called?
2.161. What is assignment operator?
2.162. What are all the implicit member functions of the class? Or what are all the functions which compiler implements for us if we do not define one?
2.163. What is conversion constructor?
2.164. What is conversion operator?
2.165. What is diff between malloc()/free() and new/delete?
2.166. What is the difference between “new” and “operator new”?
2.167. What are C++ storage classes?
2.168. What are storage qualifiers in C++?
2.169. What is a reference?
2.170. What is passing by reference?
2.171. When do use “const” reference arguments in function?
2.172. When are temporary variables created by C++ compiler?
2.173. What is virtual function?
2.174. What is pure virtual function? or what is abstract class?
2.175. What is memory alignment?
2.176. What problem does the namespace feature solve?
2.177. What is the use of ‘using’ declaration?
2.178. What is an Iterator class?
2.179. What is a dangling pointer?
2.180. Name the operators that cannot be overloaded?
2.181. What is a container class? What are the types of container classes?
2.182. What is inline function?
2.183. What is overloading?
2.184. What is overriding?
2.185. What is “this” pointer?
2.186. What happens when you make call “delete this;”?
2.187. What is name mangling in C++?
2.188. How can I handle a constructor that fails?
2.189. How can I handle a destructor that fails?
2.190. What is Virtual Destructor?
2.191. What are the differences between a C++ struct and C++ class?
2.192. What is multiple inheritance (virtual inheritance)? What are its advantages and disadvantages?
2.193. What are the access privileges in C++? What is the default access level?
2.194. What is a nested class? Why can it be useful?
2.195. What is a local class? Why can it be useful?
2.196. What is a pragma statement?
2.197. What does the Standard C++ library contain?
2.198. What is ATL?
2.199. When to use ATL versus MFC?
2.200. What are template libraries?
2.201. What are some of the COM concepts?
2.202. What is upcasting?
2.203. What is Static type checking?
2.204. What is Standard C++ include format?
2.205. How do you ensure that your cpp code works with both c and cpp programs?
2.206. Discuss friend classes in C++ and give an example of when you would use one.
2.207. Discuss the relationship between parent and child classes in C++.
2.208. Compare and contrast macros and inline functions in C++.
2.209. Compare and contrast a hashtable and a binary search tree. If you were designing the address book data structure for a handheld personal organizer with limited memory, like a Palm Treo, which one would you use?
2.210. What is segmentation fault?
2.211. What is the difference between strcpy and strncpy?
2.212. Describe cast operators.
2.213. When should you choose the C++ cast operators over C-style cast?
2.214. Describe reinterpret_cast operator.
2.215. What is a template?
2.216. What are class templates?
2.217. Give a template implementation of a Stack.
2.218. What are function templates?
2.219. Describe Multithreading concepts.
2.220. What is a critical section?
2.221. How do you test multi threaded code?
2.222. What is a critical section? What is a mutex? How do they differ?
2.223. Why is PulseEvent() not useful given an auto-reset event object?
2.224. How does a semaphore differ from the other synchronization objects?
2.225. What are the two thread creation functions you can use and which is better?
2.226. If in your process you create two additional child threads, how many threads are running in your process?
2.227. What are some testing techniques you can use to help better test your multithreaded applications?
2.228. Why isn’t everything written as just one big program, saving the necessity of linking?
2.229. What are the advantages of dynamic linking?
2.230. What are pointers?
2.231. What is reference counting and why would you use it?
2.232. What are templates and why are the used? What are the pros and cons of templates?
2.233. What is the difference between C++ structure and C++ class?
2.234. What is the difference between function overloading and function overriding?
2.235. What are the differences between a thread and a process?
2.236. What’s the difference between a semaphore and a mutex?
2.237. How can a thread avoid a busy wait for particular condition to be true? For example, how can a thread that’s reading from a queue avoid pegging a single processor machine’s CPU at 100% when the queue is empty?
2.238. What is polymorphism? Show an example.
2.239. What is encapsulation and why is it a good thing? Show an example.
2.240. What are some of the problems with multiple-inheritance? When is it OK to use multiple-inheritance?
2.241. What is the difference of semaphore, mutex and conditional variable?
2.242. What is operator overloading?
2.243. How do I debug into a DLL? I can’t seem to get it to remember my breakpoints.
2.244. Why do I get an undefined symbol for a symbol that is defined in a namespace?
2.245. How do i make it so that a variable is global to all classes of type ______?
2.246. Which casting operator should I use?
2.247. How can I delete my executable while it is running?
2.248. Given:
2.249. What are those huuuge *.csm files that seem to follow my projects everywhere?
2.250. How do I use a #pragma to stop the compiler from issuing a warning?
2.251. When dealing with databases, what is the difference between keys and indices?
2.252. How would I write a program to make a cellular phone call?
2.253. Why do I have to call the c_str() member function of the String class?
2.254. How can I have a class which allows only one object to be created?
2.255. What are the different techniques for C++ debugging? Mention the pros and cons of each approach? Which approach you would recommend?
2.256. Why isn’t everything written as just one big program, saving the necessity of linking?
3 Glossary