Link to home
Start Free TrialLog in
Avatar of lhgarrett
lhgarrett

asked on

foreach - supported in C coding language?

I'm writing a program in C on the PC. I want to loop as a function of the number of array elements in the same way I'm used to doing in Unix c-shell scripts (an implied counter):

  set NameList = ( Joe Bob Karen Larry )
  foreach Name ( $NameList )
     processing...
  end

-- or --

  foreach Name ( Joe Bob Karen Larry )
     processing...
  end

Can I do this, or do I have to know the size of the array in advance and do it like,

   #define NAME_SIZE 4
   int i;
   for(i = 0; i < NAME_SIZE; i++)
   {
      processing...
   }

If it's not supported, can you suggest the code to implement a C function that would work like foreach?
Avatar of ozo
ozo
Flag of United States of America image

How do you declare the array?
Avatar of rbr
rbr

Try this
#define NAME_SIZE 4
char *NameList[NAME_SIZE]={"Joe","Bob","Karen","Larry"};


for (i=0;i<NAME_SIZE;i++) {
.... Do what ever you want
.... For accessing the array use NameList[i]

}
char *NameList[NAME_SIZE]={"Joe","Bob","Karen","Larry",'\0'};
int i=0;
while (NameList[i]!='\0') {
   /* processing...  */
   i++;
}
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lhgarrett

ASKER

To rbr:

Thanks, but the idea I was looking for was a way of not having to count the elements in the array.
> while (NameList[i]!='\0') {
This will work, however...

> for( i=0;i<sizeof(NameList)/sizeof(NameList[0]);i++ )
This actually is closer to what I was looking for!

Points to ozo this time, but thanks to both of you!!!