Node:Arrays and hidden operators, Next:, Previous:Postfix and prefix ++ and --, Up:Hidden operators and values



Arrays and hidden operators

Hidden operators can simplify dealing with arrays and strings quite a bit. Hiding operators inside array subscripts or hidding assignments inside loops can often streamline tasks such as array initialization. Consider the following example of a one-dimensional array of integers.

#include <stdio.h>

#define ARRAY_SIZE 20

/* To shorten example, not using argp */
int main ()
{
  int idx, array[ARRAY_SIZE];

  for (idx = 0; idx < ARRAY_SIZE; array[idx++] = 0)
    ;

  return 0;
}

This is a convenient way to initialize an array to zero. Notice that the body of the loop is completely empty!

Strings can benefit from hidden operators as well. If the standard library function strlen, which finds the length of a string, were not available, it would be easy to write it with hidden operators:

#include <stdio.h>

int my_strlen (char *my_string)
{
  char *ptr;
  int count = 0;

  for (ptr = my_string; *(ptr++) != '\0'; count++)
    ;

  return (count);
}

/* To shorten example, not using argp */
int main (int argc, char *argv[], char *envp[])
{
  char string_ex[] = "Fabulous!";

  printf ("String = '%s'\n", string_ex);
  printf ("Length = %d\n", my_strlen (string_ex));

  return 0;
}

The my_strlen function increments count while the end of string marker \0 is not found. Again, notice that the body of the loop in this function is completely empty.