[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 248
  • Last Modified:

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?
0
lhgarrett
Asked:
lhgarrett
1 Solution
 
ozoCommented:
How do you declare the array?
0
 
rbrCommented:
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]

}
0
 
ahoffmannCommented:
char *NameList[NAME_SIZE]={"Joe","Bob","Karen","Larry",'\0'};
int i=0;
while (NameList[i]!='\0') {
   /* processing...  */
   i++;
}
0
Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

 
ozoCommented:
char *NameList[]={"Joe","Bob","Karen","Larry"};
for( i=0;i<sizeof(NameList)/sizeof(NameList[0]);i++ )
0
 
lhgarrettAuthor Commented:
To rbr:

Thanks, but the idea I was looking for was a way of not having to count the elements in the array.
0
 
lhgarrettAuthor Commented:
> 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!!!
0

Featured Post

2018 Annual Membership Survey

Here at Experts Exchange, we strive to give members the best experience. Help us improve the site by taking this survey today! (Bonus: Be entered to win a great tech prize for participating!)

Tackle projects and never again get stuck behind a technical roadblock.
Join Now