Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic jump to label in C

Tags:

c

I would like to display the output - numbers 1 to 5, followed by 4-5 infinitely. Is there any way i can pass the value of i(4) instead of the character i in goto1. Or is there any other efficient way of realizing this without illustrating all the options as in switch(i.e case 1: goto1(c1) ,etc..).

The main aim is to jump to a statement whose label is computed within the program.

#define goto1(i) \
goto c##i

int main(){    
    c1 : printf(" num is 1 \n");
    c2 : printf(" num is 2 \n");
    c3 : printf(" num is 3 \n");
    c4 : printf(" num is 4 \n");
    c5 : printf(" num is 5 \n");

    int i=4;
    goto1(i);
}
like image 769
ceedee Avatar asked Mar 29 '13 11:03

ceedee


People also ask

What is the use of jump statement in C?

The main uses of jump statements are to exit the loops like for, while, do-while also switch case and executes the given or next block of the code, skip the iterations of the loop, change the control flow to specific location, etc. There are 4 types of Jump statements in C language. Return Statement.

How do you label a variable in C?

A Label in C is used with goto and switch statements. A label is followed by a colon and what makes it special is that it has the same form as a variable name. Also,it can be adjoined with any statement in the same function as the goto. The label differs from the other statements of its kind is the scope.

Are label variables a bad idea in C?

Actually, even "C Reference Manual" itself said that "Label variables are a bad idea in general; the switch statement makes them almost always unnecessary" (see "14.4 Labels" ). Show activity on this post. The switch ... case statement is essentially a computed goto. A good example of how it works is the bizarre hack known as Duff's Device:

What are “Goto” and “labels” in C?

Everybody who has programmed in C programming language must be aware about “goto” and “labels” used in C to jump within a C function. GCC provides an extension to C called “local labels”.


2 Answers

If you are ... adventurous (or do I mean silly?), you can use a GCC extension Labels as Values.

6.3 Labels as Values

You can get the address of a label defined in the current function (or a containing function) with the unary operator ‘&&’. The value has type void *. This value is a constant and can be used wherever a constant of that type is valid. For example:

 void *ptr;
 /* ... */
 ptr = &&foo;

To use these values, you need to be able to jump to one. This is done with the computed goto statement1, goto *exp;. For example,

 goto *ptr;

Any expression of type void * is allowed.

One way of using these constants is in initializing a static array that serves as a jump table:

 static void *array[] = { &&foo, &&bar, &&hack };

Then you can select a label with indexing, like this:

 goto *array[i];

Note that this does not check whether the subscript is in bounds—array indexing in C never does that.

Such an array of label values serves a purpose much like that of the switch statement. The switch statement is cleaner, so use that rather than an array unless the problem does not fit a switch statement very well.

Another use of label values is in an interpreter for threaded code. The labels within the interpreter function can be stored in the threaded code for super-fast dispatching.

You may not use this mechanism to jump to code in a different function. If you do that, totally unpredictable things happen. The best way to avoid this is to store the label address only in automatic variables and never pass it as an argument.

An alternate way to write the above example is

 static const int array[] = { &&foo - &&foo, &&bar - &&foo,
                              &&hack - &&foo };
 goto *(&&foo + array[i]);

This is more friendly to code living in shared libraries, as it reduces the number of dynamic relocations that are needed, and by consequence, allows the data to be read-only.

The &&foo expressions for the same label might have different values if the containing function is inlined or cloned. If a program relies on them being always the same, __attribute__((__noinline__, __noclone__)) should be used to prevent inlining and cloning. If &&foo is used in a static variable initializer, inlining and cloning is forbidden.


Footnotes

[1] The analogous feature in Fortran is called an assigned goto, but that name seems inappropriate in C, where one can do more than simply store label addresses in label variables.

Under no circumstances should this be taken as a recommendation to use the feature. The computed goto was eventually removed from Fortran; it is best left in the dustbin of history.

like image 131
Jonathan Leffler Avatar answered Sep 27 '22 19:09

Jonathan Leffler


Are you asking for a jump table? If you are using gcc: It has a jump table mechanism.

#include <stdio.h>

int main()
{
    unsigned char data[] = { 1,2,3,4,5,4,5,0 };
    // data to "iterate" over, must be 0-terminated in this example

    void *jump_table[] = { &&L00, &&L01, &&L02, &&L03, &&L04, &&L05 };
    // you should fill this with all 256 possible values when using bytes as p-code

    unsigned char *p = data;

    begin:
        goto *jump_table[ *p ];

    L00:
        return 0; // end app
    L01:
        printf("num %i\n", (int)*p);
        goto next;
    L02:
        printf("num %i\n", (int)*p);
        goto next;
    L03:
        printf("num %i\n", (int)*p);
        goto next;
    L04:
        printf("num %i\n", (int)*p);
        goto next;
    L05:
        printf("num %i\n", (int)*p);
        goto next;
    L06:
    L07:
    // ...
    LFF:
        goto next;

    next:
        ++p;            // advance the data pointer to the next byte
        goto begin;     // start over

    return 0;
}

The pro about this method is that you spare the large switch statement.

like image 25
max.haredoom Avatar answered Sep 27 '22 19:09

max.haredoom