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

5
  • the consts 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). Commented Feb 8, 2016 at 14:48
  • Thanks, but when you are calling the function what does (uint8_t *) before BANNER_STR refer to? Commented Feb 8, 2016 at 14:50
  • 1
    it casts BANNER_STR from const char* to uint8_t* before passing it to the function. Commented Feb 8, 2016 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. Commented Feb 8, 2016 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 Commented Jan 9, 2017 at 4:48

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

2 Comments

given that it's casting away const, I wouldn't call it "correct".
you are right, maybe "valid" is more "correct" for this

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.