Foreach loop in C | SoloLearn: Learn to code for FREE!

+2

Foreach loop in C

hi guys, i'm trying to make a foreach loop in C, i wrote it two times (lines 6 and 9), but the first loop doesn't work correctly, if i decommented it, it gives me "no output". the second loop is the same of first's except i wrote a statement out of the loop, why only second one work well? which is the difference? https://code.sololearn.com/clMTythoeYwZ/?ref=app

9/25/2017 5:34:17 AM

Daniele

8 Answers

New Answer

+4

Or better yet: for(p = ls; p < &ls[sizeof(ls)/sizeof(ls[0])]; p++) { printf("%d\n", *p); }

+5

p = ls; for(int i = 0; i < sizeof(ls)/sizeof(ls[0]); p++, i++) { printf("%d\n", *p); }

+4

It's not a for each loop it's a for loop, there is a difference. The for loop is used to run through a code block a specific number of times. It uses three parameters. The first one initializes a counter and is always executed once before the loop. The second parameter holds the condition for the loop and is checked before each iteration. The third parameter contains the increment of the counter and is executed at the end of each iteration. In your commented out code you have an assignment taking place as the third parameter "p = &ls[I++]" but you are trying to print out what p is pointing to in the loop 'printf("%d\n", *p);' before anything has been assigned to p. This is bad and the code playground is spitting it out. Unfortunately, the code playground has poor error messages so all you get is the program terminatng and "no output" because the program is terminated before any output is generated.

+2

Hi, have you tried sizeof(ls)/sizeof(ls[0])? I tried your code seems incompatible with Playground, there was no output. Hth, cmiiw

0

thank you for replying, yeah it was a very silly mistake (thanks @Gordie ), i didn't understand it before because the code playground gave me no error...🙈 @ChaoticDawg thanks for your solution, it is simpler than mine, i like it! @Martin Taylor yeah i know it is not a foreach loop but i would like to create something similar :)

0

you're right @Gordie i didn't know it was possible to point an array directly (p = ls), i thought i had to point each element separately