I'm trying to learn more about kernels, so naturally I started to program one. I'm using tutorials from here. Right now I have modified the printf() that was supplied there. It used goto and I didn't like that.

Can anyone see anything wrong with this code? It worked fine when I tested it.

printf("hello %c world %c",'x','y')

int printf(const char* restrict format, ...)
   va_list parameters;
   va_start(parameters, format);

   int written = 0;
   size_t amount;

   while(*format != '\0')
      if (*format != '%')
    amount = 1;
    while(format[amount] && format[amount] != '%') //print every character until, % is encountered.
    print(format, amount);
    format += amount;       
    written += amount;
      switch(*(++format)) //since format points now to %, move on step
         case 'c':
            format++;   //prepare next char
        char c = (char)va_arg(parameters, int);
        print(&c, sizeof(c));
    return written;

And print(), left completely unmodified:

static void print(const char* data, size_t data_length)
    for ( size_t i = 0; i < data_length; i++ )
        putchar((int) ((const unsigned char*) data)[i]);

1 Answer 1

  • You may need to document that this currently only works for the c option. Others may assume otherwise that this can support all or most of them. Of course, you don't have to do that since this is merely a reinvention of the wheel.

  • Make sure to keep your indentation consistent. It seems you're mostly using four spaces for it, so it should be done everywhere. You should especially fix it in the large if statement.

  • This looks a little unusual:


    I assume you're doing this to avoid duplication, but based on your current code, it looks like you can still put it in the switch body without repetition. Not having the increment in the statement itself may help with readability, too.

  • You never check for errors, which is what the standard function does. If an error occurs, you should set the error indicator ferror and then return a negative value.

    Be sure you're reading the documentation on this function to help improve your own.


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.