Loop in C help!
My friends tell me that a special loop exists that isn't a 'while' loop or a 'do while' loop.
Does anyon开发者_JS百科e know what it's called and the correct syntax for it's use?
A for loop maybe?
for (i = 0; i < 15; ++i) {
/* do stuff */
}
A goto loop perhaps? That is pretty special.
start:
/* do stuff */
if ( !done ) goto start;
There are 3 kind of loops in c
.
The for loop: http://cprogramminglanguage.net/c-for-loop-statement.aspx
for (initialization_expression;loop_condition;increment_expression){
// statements
}
The while loop: http://cprogramminglanguage.net/c-while-loop-statement.aspx
while (expression) {
// statements
}
The do while loop: http://cprogramminglanguage.net/c-do-while-loop-statement.aspx
do {
// statements
} while (expression);
And you can emulate loops with a function ofcourse:
Emulating a do while loop:
void loop(int repetitions){
// statements
if(repetitions != 0){
loop(repetitions - 1);
}
}
Emulating a while loop:
void loop(int repetitions){
if(repetitions != 0){
// statements
loop(repetitions - 1);
}
}
A signal handler loop perhaps? That is pretty special.
#include <signal.h>
void loop(int signal)
{
if ( !done ) {
/* do stuff */
raise(SIGINT);
}
}
int main() {
signal(SIGINT, loop);
raise(SIGINT);
return 0;
}
A setjmp loop perhaps? That is pretty special.
static jmp_buf buf;
int i = 0;
if ( setjmp(buf) < end ) {
/* do stuff */
longjmp(buf, i++);
}
There's the for
loop, although I don't know how special I'd consider it.
and don't forget recursion
void doSomething(int i)
{
if(i > 15)
return;
/* do stuff */
doSomething(i + 1);
}
you left out a for(;true;) loop
My answer here could help you understand how C for loop works
infinite loop ?
for(;;){ }
I like this one :-)
A Y combinator loop? That's special enough to be apple only (for now). Also special enough to leak memory all over the place
#include <stdio.h>
#include <Block.h>
typedef void * block;
typedef block (^block_fn)(block);
typedef void (^int_fn)(int);
int main(int argc, char ** argv) {
block_fn Y = ^ block(block f) {
return ((block_fn) ^ block(block_fn x) {
return x(x);
})(^ block(block_fn x) {
return ((block_fn)f)(Block_copy(^ block(block y) {
return ((block_fn)(x(x)))(y);
}));
});
};
int_fn loop = Y(^ block(int_fn f) {
return Block_copy(^ (int a) {
if (a <= 0) {
printf("loop done\n");
} else {
printf("loop %d\n", a);
f(a - 1);
}
});
});
loop(10);
return 0;
}
精彩评论