1
\$\begingroup\$

In AVR-libc page 143 the implementation of the function uart_putchar() is typical as the following:

#include <stdio.h>

static int uart_putchar(char c, FILE *stream);

static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);

static int
uart_putchar(char c, FILE *stream)
{
if (c == '\n')
  uart_putchar('\r', stream);
loop_until_bit_is_set(UCSRA, UDRE);
UDR = c;
return 0;
}
int
main(void)
{
  init_uart();
  stdout = &mystdout;
  printf("Hello, world!\n");
  return 0;
}

I know that we can redirect a specific stream to a stdout or stdin using fdevopen().

But is not the variable stream is not used in this function? Why is there such a variable that not used by the function? Is that because the fdevopen() pointers to functions parameters?

\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

You are not specifically creating a UART stream. You are creating a generic stream that happens to go to the UART.

Many times streams can go to different places. As the variable type FILE suggests it's commonly to a file - such as on an SD card. In these situations the FILE parameter is essential for the function to know exactly where the data is to go to.

For the UART it is irrelevant since there is only one place it can go - the UART.

The functions that interact with whatever you implement expect a certain prototype and pass certain parameters. Whether you use those parameters or not you have to accept them and have them in your function prototype - otherwise you just can't compile your code (you have a mismatch in the function pointer definitions).

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Shouldn't the compiler throw a warning at compile time because of that unused variable? \$\endgroup\$
    – NAND
    Feb 19 at 13:04
  • 1
    \$\begingroup\$ @NAND It is used in this case - it's passed to the recursive line feed / cr call. Plus not all compilers have it turned on by default. \$\endgroup\$
    – Majenko
    Feb 19 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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