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?
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?
How do you declare the array?
Try this
#define NAME_SIZE 4
char *NameList[NAME_SIZE]={"Joe ","Bob","K aren","Lar ry"};
for (i=0;i<NAME_SIZE;i++) {
.... Do what ever you want
.... For accessing the array use NameList[i]
}
#define NAME_SIZE 4
char *NameList[NAME_SIZE]={"Joe
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","K aren","Lar ry",'\0'};
int i=0;
while (NameList[i]!='\0') {
/* processing... */
i++;
}
int i=0;
while (NameList[i]!='\0') {
/* processing... */
i++;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
To rbr:
Thanks, but the idea I was looking for was a way of not having to count the elements in the array.
Thanks, but the idea I was looking for was a way of not having to count the elements in the array.
ASKER
> while (NameList[i]!='\0') {
This will work, however...
> for( i=0;i<sizeof(NameList)/siz eof(NameLi st[0]);i++ )
This actually is closer to what I was looking for!
Points to ozo this time, but thanks to both of you!!!
This will work, however...
> for( i=0;i<sizeof(NameList)/siz
This actually is closer to what I was looking for!
Points to ozo this time, but thanks to both of you!!!