最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - puts() implementation using putchar() - Stack Overflow

programmeradmin0浏览0评论

Of late, I have been reading an old text on embedded programming using C and C++:

Programming Embedded Systems in C and C++ Michael Barr

Under Putting It All Together->Working with Serial Ports, the author first presents the following implementation of putchar(), and a subsequent implementation of puts(), which in turn uses putchar():

/**********************************************************************
*
* Method: putchar()
*
* Description: Write one character to the serial port.
*
* Notes:
*
* Returns: The transmitted character is returned on success.
* -1 is returned in the case of an error.
*
**********************************************************************/
int
SerialPort::putchar(int c)
{
  if (pTxQueue->isFull())
  {
    return (-1);
  }

  // Add the character to the transmit FIFO.
  pTxQueue->add((char) c);

 // Start the transmit engine (if it's stalled).
  scc.txStart(channel);

  return (c);

} /* putchar() */

/**********************************************************************
*
* Method: puts()
*
* Description: Copies the null-terminated string s to the serial
* port and appends a newline character.
*
* Notes: In rare cases, this function may return success though
* the newline was not actually sent.
*
* Returns: The number of characters transmitted successfully.
* Otherwise, -1 is returned to indicate error.
*
**********************************************************************/
int
SerialPort::puts(const char * s)
{
  const char * p;

  // Send each character of the string.
  for (p = s; *p != '\0'; p++)
  {
   if (putchar(*p) < 0) break;
  }

  // Add a newline character.
  putchar('\n');

  return ((p - s) + 1);

} /* puts() */

I understand that a for loop is equivalent to a while as noted in the following discussion: when exactly the increment happens in a for loop in C++?

Putting together, I presume the above implementation of puts() has the following logical flaws:

a) If no character could be output, then based on the implementation, puts() would still return 1, as p would be pointing to the same address as s.

b) Assuming that the for loop executes only once, i.e., a single character could be output before putchar() returns -1, p would have been incremented to point to s + 1. So in effect, puts() would return 2 instead of 1.

So obviously, the flaw lies in the return statement within puts, which adds 1 to the difference between p and s; it should simply be return (p -s) instead.

The return should also account for the case of -1 from putchar() when no characters could be output.

Is this understanding correct?

发布评论

评论列表(0)

  1. 暂无评论