3
\$\begingroup\$

I implemented a function that prints all the numbers from the Fibonacci sequence until max_num. The minimum value allowed is 0 (so, fib(0) prints 1). It works until 92, and I want to know how to improve the code, in general.

void fib(unsigned int max_num)
{
    unsigned long fib_num = 1;
    unsigned long fib_temp = 0;
    size_t count = 0;

    if (max_num < 0)
    {
        fprintf(stderr, "Please, enter a non-negative number\n");
        return;
    }

    for (; count <= max_num; count++)
    {
        printf("%lu\n", fib_num);
        fib_num += fib_temp;
        fib_temp = fib_num - fib_temp;
    }
}
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

Consider documenting this function with something like doxygen. At a quick glance, your function can be interpreted two different ways: Print out fib(0), fib(1), ..., or print out all Fibonacci numbers less than or equal to max_num. Documentation will clarify that.

max_num will never be negative. It is defined as an unsigned int, which means it can never hold a negative value. So this:

if (max_num < 0)
{
    fprintf(stderr, "Please, enter a non-negative number\n");
    return;
}

will never happen. (Try calling fib(-2), see what happens)

(Optional) Put size_t count = 0 inside the loop if you can? (You may have to add -std=c99 or something like that to make it work)

for (size_t count = 0; count <= max_num; count++)
{
    printf("%lu\n", fib_num);
    fib_num += fib_temp;
    fib_temp = fib_num - fib_temp;
}
\$\endgroup\$
4
  • \$\begingroup\$ Thanks a lot for the answer! I heard some people saying I should stick to the c89 mode. In your opinion, which one is the best? \$\endgroup\$ Commented Aug 23, 2016 at 0:33
  • 1
    \$\begingroup\$ It has a lot to do with how much of the market supports the language... It may have been at the time a better idea to use C89 over C99 because very few compilers supported C99. This isn't true anymore. It might even be better to use C11. (Which I believe is -std=c11). A large part is do you need to support C89? C99? If not, I would just do C99, the for-loop syntax for C89 is particularly annoying to me. \$\endgroup\$
    – Dair
    Commented Aug 23, 2016 at 0:50
  • \$\begingroup\$ For reference there are answers here: stackoverflow.com/a/11926008/667648 That coincide with my comment. \$\endgroup\$
    – Dair
    Commented Aug 23, 2016 at 0:53
  • \$\begingroup\$ @LúcioCardoso The only more or less relevant compiler not supporting C99 is VS C compiler afaik. But C is mostly broken under Windows, similar to OpenGL. It works, with a few quirks, but it's not for serious development. \$\endgroup\$
    – ljrk
    Commented Aug 24, 2016 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.