F
Flash Gordon
Afghan said:
You use printf without a function prototype in scope. This invokes
undefined behaviour because printf is a varidac function. ALWAYS include
stdio.h before using printf and other headers as appropriate before
using other functions.
In your first CountBits function you assume that int is 32 bits. int
could be as small as 16 bits. If you want a number of at least 32 bits
use long. In addition it is not guaranteed to work properly with
negative numbers, so you should use an unsigned type such as unsigned long.
You should acknowledge the original author of Duff's device. Tom Duff
deserves recognition for his highly warped thinking. I suggest a link
over to http://www.lysator.liu.se/c/duffs-device.html unless someone can
suggest a better link.
int foobar();
is *not* a function prototype. To be correct I believe you should say:
| Are the following two function declarations same?
|
| int foobar(void);
| int foobar();
The program that then passes parameters to foobar2 (which uses the
non-prototype form) invokes undefined behaviour which means that
*anything* can happen. There are even ways it could cause a program to
crash! You should point out that even though it might work it is not
required to.
Your example:
| #include <stdio.h>
| int main()
| {
| float a = 12.5;
| printf("%d\n", a);
| printf("%d\n", *(int *)&a);
| return 0;
| }
may also not behave as *you* expect since it invokes undefined
behaviour. If I recall correctly one implementation I have would print
12 on the first line and other implementations I have definitely would not.
You don't always check the value returned by malloc before using it. You
should.
In the following example you say there will not be a linker error:
| a.c
| ---
|
| int a;
|
| b.c
| ---
|
| int a = 10;
|
| main.c
| ------
|
| extern int a;
| int main()
| {
| printf("a = %d\n",a);
| return 0;
| }
Apart from the fact it gives a warning with gcc on my implementations...
markg@brenda:~$ gcc a.c b.c main.c
main.c: In function ‘main’:
main.c:4: warning: incompatible implicit declaration of built-in
function ‘printf’
On other systems, or with other options to gcc, it will generate an
error for the multiple declarations. e.g.
markg@brenda:~$ gcc -fno-common a.c b.c main.c
main.c: In function ‘main’:
main.c:4: warning: incompatible implicit declaration of built-in
function ‘printf’
/tmp/cc7nbS36.o
/tmp/cc6wAnSK.o
collect2: ld returned 1 exit status
Some implementations will generate a warning or error even without
special options.
Your example of a definition of the offsetof macro invokes undefined
behaviour. It is *not* possible to implement it portably and this is
probably why it is provided in a standard header.
Some of your other example questions are, in my opinion, plain stupid.
This does not mean that they are never asked of course!
I would also suggest you include references to other useful resources,
in particular the comp.lang.c FAQ at http://c-faq.com/
I'm sure others will have more comments.