Home > OS >  Size_t and buffer in print function
Size_t and buffer in print function

Time:11-06

I have the following function to print out text to an LCD. Everything works, although I'm having some trouble understanding how it works and why it's written this way.

I understand it takes a string array, and loops through it to write each character to the LCD.

What I don't understand is why does it use a buffer instead of just accessing the str variable directly. And why does it return the length of the string that was written out. Also why does my write function also need to return size_t.

// This will print character string to the LCD
size_t print(const char str[]) {
  if (str == NULL) return 0;

  const uint8_t *buffer = (const uint8_t *)str;
  size_t size = strlen(str);
  size_t n = 0;

  while (size--) {
    if (write(*buffer  )) n  ;
    else break;
  }
  return n;

CodePudding user response:

why does it use a buffer instead of just accessing the str variable directly?

Because the write() function takes a uint8_t parameter, but str contains char. So this avoids having to write a cast in the write() call. It would work just as well using

if (write((uint8_t)*(str  ))) n  ;

but this is harder to read.

why does it return the length of the string that was written out?

So the caller will know how many characters were successfully written, in case write() reports an error in the middle of the string (by returning 0).

why does my write function also need to return size_t?

I can't think of a reason, other than for consistency with functions. write() should just return either 1 when it writes successfully or 0 when it fails.

CodePudding user response:

Please checkout the code changes below with the comments

size_t print(const char *str) { // As it always degrades into a pointer!
  if (str == NULL) {
    return 0;
  } // Always use braces - do not wish to get you pants down!

  // Is this needed? const uint8_t *buffer = (const uint8_t *)str;
  // Do not need this - counting a string twice ! size_t size = strlen(str);
  // Not requires dsize_t n = 0;

  //while (size--) {
  for (size_t n = 0; str[n]; n  ) {  
    write(buffer[n]); //if (write(*buffer  )) n  ;
    // else break; for loop removes the requirement
  }
  return n;

}

Please note write is a part of unidstd see unistd - So some confusion here

  •  Tags:  
  • c
  • Related