The following code:
#include <cstdlib>
#include <iostream>
using namespace std;
int function(void)
{
static int i,state=0;
switch(state)
{
case 0: goto labeL0;
case 1 :goto labeL1;
}
labeL0:
for (i = 0; i < 10; i++)
{
state=1;
return i;
labeL1:;
}
}
int main(int argc, char *argv[])
{
cout << function() << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
fails. I mean it returns only 0
instead of 0,1,2,...
I wanted just use label and goto
statements to implement such functions. It is for practice (let's say homework), but I can't get it to work. Is this even possible?
How can I use goto
and label statements so that this function prints 0 1 2...
so on?
It's not clear to me exactly what you're trying to do. If your goal is
jsut to use goto
, the simplest solution is to implement the algorithm
exactly as you'ld normally do, replacing looping constructs wit goto
;
i.e. instead of:
for ( int i = 0; i < 10; ++ i ) {
std::cout << i << std::endl
}
you could write:
int i = 0;
goto label1:
label2:
std::cout << i << std::endl;
++ i;
label1:
if ( i < 10 ) goto label2;
Back in the old days, with Fortran IV, this is what we actually did. There's absolutely no reason to do it today (except maybe obfuscation).
I wonder, however, given the static variables, if you're not trying to implement some sort of co-routine; that each time you call the function, you output one higher than the previous time. In this case, I'd recommend maintaining the state in a class, rather than using static variables. In addition the function will need some sort of return value so that the caller will know when it's finished, and the caller will have to loop. Something like the following should do the trick:
class CoRoutine
{
int i;
public:
CoRoutine() : i( 0 ) {}
bool function()
{
if ( i < 10 ) {
std::cout << i <<std::endl;
++ i;
}
return i < 10;
}
};
int
main()
{
CoRoutine c;
while ( c.function() ) {
}
return 0;
}
(There's still no need for goto
, of course.)