0

I am very new to c++ and don't know all the rules quite yet. I am trying to fix this function by returning an int from a const char *. This is what it looks like:

int UARTwrite(const char *pcBuf, uint32_t ui32Len)
{
    const char* p = pcBuf;
    int i = 0;
    for( i = 0; i < ui32Len; ++i )
    {
        printf( "%c", *p );
        ++p;
    }
    return(std::cout << p << ' ' << static_cast<int> (p)); // error: invalid static_cast from type 'const char*' to type 'int'
}

before there was no return, so I tried a static_cast which didn't work. I commented the error the keeps popping up. Any help is appreciated.

  • `return (std::cout …)` will return an `ostream` object, not an `int` ... – ChrisMM Jun 02 '20 at 14:36
  • 1) Please provide [mre]. 2) If you are new to C++, you should consider learning from a [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of coding randomly. – Algirdas Preidžius Jun 02 '20 at 14:36
  • 1
    You need to explain the semantics you want. Does `pcBuf` point to a C string like `"42"`, and which you need to parse into the integer value `42`? Or do you want the integer value equivalent to the address, or the integer value of the first character in the string, or ... ? – Useless Jun 02 '20 at 14:36
  • Note that `return` has a very specific meaning in C++. It sounds to me like you mean "print an `int`" or "display an `int`" instead of "return an `int`". If this isn't the case, then the duplicate might not be appropriate. – François Andrieux Jun 02 '20 at 14:38
  • But yeah, the proximate error is just what @ChrisMM said - the result of a `cout << ...;` statement is _not_ just the last expression. – Useless Jun 02 '20 at 14:38
  • @FrançoisAndrieux ok that makes sense. I have a background in java so that is where my mind went. What would you suggest then? – Alexander Wood Jun 02 '20 at 14:48
  • @AlexanderWood The linked duplicate has many possible solutions. `std::stringstream` and `std::atoi` will both work. Consider using `std::string` instead of passing pointers and sizes. – François Andrieux Jun 02 '20 at 14:51
  • 1
    Something called `UARTwrite` that returns an `int` probably wants return one of: 1. the number of bytes actually and successfully written to the UART, or 2. a 0/1 indicating failure/success (a true/false `bool` would be better here, but this could interface with an older code base before `bool` was in the standard). What does your function need to do? Are you updating code in a current code base? Or are you making code for a new code base? If it's the latter you should have your requirements tell you what this function needs to do. – JohnFilleau Jun 02 '20 at 14:57

0 Answers0