2

In the function declaration below the second argument is a const pointer to const data.

ti_rc_t ti_uart_write_buffer(const ti_uart_t uart, const uint8_t *const data, uint32_t len);

Below is example code calling the function. Why is there a (uint8_t *) before BANNER_STR. Is this the usual syntax for passing a const pointer to a const data to a function? Are there other valid syntax?

#define BANNER_STR ("Hello, world!\n\n")
ti_uart_write_buffer(TI_UART_0, (uint8_t *)BANNER_STR, sizeof(BANNER_STR));

Thanks

ultrasonic bananna
  • 193
  • 1
  • 3
  • 12
  • the `const`s there are a promise by the function that it won't modify the pointer (not that that makes much sense) or the data pointed to - it is not a restriction on the caller (ie. the caller can pass in a `const` or non-`const` pointer to `const` or non-`const` data). – Sander De Dycker Feb 08 '16 at 14:48
  • Thanks, but when you are calling the function what does `(uint8_t *)` before BANNER_STR refer to? – ultrasonic bananna Feb 08 '16 at 14:50
  • 1
    it casts `BANNER_STR` from `const char*` to `uint8_t*` before passing it to the function. – Sander De Dycker Feb 08 '16 at 14:51
  • 1
    This is just bad code. Don't (miss)use macros that way. Just define a normal `const` variable array or pointer with the text. – too honest for this site Feb 08 '16 at 15:12
  • `char` and `uint8_t` are usually incompatible types; a cast is necessary to do pointer-based aliasing like this. You are focusing on `const` but that is a red herring. They could have written `(const uint8_t *)` with the same end result. The `uint8_t *` value result of the cast will be implicitly converted to `const uint8_t *` to match the function parameter anyway – M.M Jan 09 '17 at 04:48

1 Answers1

2

The define BANNER_STR is an array of characters as its type, in other words a string. And therefore in your function call you need to cast this argument to avoid compiler warnings but this is a valid way to call this function.

An other valid syntax would be instead of using define directive to declare a constant variable which contains the string to write:

const char banner_str[] = "Hello, world!\n\n";
ti_uart_write_buffer(TI_UART_0, (uint8_t *)banner_str, sizeof(banner_str));
Frodo
  • 749
  • 11
  • 23