I\'m trying to write a basic practice with C, working with Binary and Hex. I made a method to print the multiples of 2 (powers of 2) and a separate method to print out the Hex f
You run into problems because you've not provided a prototype for printhex()
before you use it.
Either put printhex()
physically before print2()
in the source file, or add a declaration:
extern void printhex(unsigned int u);
before print2()
is defined. (Don't declare printhex()
inside print2()
; even though it is syntactically legal, it is bad practice to do so.)
When the compiler runs across the call printhex(temp)
, it assumes (under C89 rules) that it is a function that returns an int
with an indeterminate argument list (but not one which is formally a variable argument list — varargs functions like printf()
must always have a prototype in scope). When you subsequently define it as returning void
, it gets upset and reports the conflicting type error. Under C99 rules, you are supposed to have a prototype in scope before using a function.
I'd like to comment on your layout; it's a little unorthodox.
The function definitions don't need as many blanks in them (use less white space in the function definitions):
void print2 ()
void printhex (unsigned int u)
would be:
void print2(void)
void printhex(unsigned int u)
if I were writing them. I write functions with the explicit (void)
in the definition so it matches the prototype notation for the function. Actually, if I was writing them, they'd more likely be prefixed with static
. If the function I write is not going to be used outside the source file it is in, then I make it static automatically. Further, if the function is defined as static before it is used, then I don't need a second declaration of the function. If a function is not static, there should, in my book, be a header that declares the function, and that header should be used in both the file that defines the function and in the files that use the function. This ensures consistency.
Also, you use abs(temp)
which is slightly odd; it is a long-winded way of converting the unsigned int
to a signed int
, but you'd do better to write:
printf("%u\n", temp);
Finally, I'd suggest you use more white space in the for
loop:
for (j = 0; j < bits; j++)
No space before commas or semicolons; spaces around binary operators (but not unary operators, or very tightly binding operators such as subscripts or member (.
or ->
) operators).
Your output interleaves hex with decimal; you might find it better to use:
printf("%10u ", temp);
to put the decimal value right justified on the line, leaving the hex to appear after it on the same line.
You're trying to use (call) printhex
before you declare it. Either forward declare it by saying void printhex (unsigned int u)
or void printhex (unsigned int)
or move the definition, to before print2
.