Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Arrays and hidden operators

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.

 
 
  Published under free license. Design by Interspire