1. Enable all the warnings, eg.
Code:
$ gcc bar.c
$ gcc -W -Wall -ansi -pedantic -O2 bar.c
bar.c: In function `main':
bar.c:9: warning: implicit declaration of function `atof'
bar.c:11: warning: unknown conversion type character `.' in format
bar.c:11: warning: too many arguments for format
bar.c: In function `dectohex':
bar.c:17: warning: 'num1' might be used uninitialized in this function
bar.c: In function `main':
bar.c:13: warning: control reaches end of non-void function
2. Lack of indentation, and omitting braces where you think they are optional (when in fact they are not) will kill you every time.
Code:
#include <stdio.h>
void dectohex(float num);
int main(int argc, char **argv)
{
float num2;
if (argc >= 2)
num2 = atof(argv[1]);
else
scanf("%2.1f", &num2);
dectohex(num2);
}
void dectohex(float num)
{
float num1;
int int_part;
unsigned int i, pos = sizeof(int) * 8 - 1;
const unsigned int int_msb = 1 << (sizeof(int) * 8 - 1);
int_part = num1;
num1 -= int_part;
if (int_part < 0) {
putc('-', stdout);
int_part = -int_part;
num1 = -num1;
}
for (i = 0; pos; i++, pos--) {
if (int_part & (int_msb >> i))
break;
}
for (; pos; pos--) {
putc(((int_part & (1 << pos)) >> pos) + '0', stdout);
}
putc((int_part & 1) + '0', stdout);
if (num1)
putc('.', stdout);
while (num1) {
num *= 2;
putc(((int) num1 & 1), stdout);
num1 -= (int) num1;
}
}
Can you now spot the infinite loop?