Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do we use goto *expr; in C?

Tags:

c

gcc

goto

| GOTO '*' expr ';'

I've never see such statements yet,anyone can bring an example?

like image 783
assem Avatar asked Mar 16 '11 20:03

assem


People also ask

Why goto is used in C?

As the name suggests, goto is used to transfer the program control to a predefined label. The goto statment can be used to repeat some part of the code for a particular condition. It can also be used to break the multiple loops which can't be done by using a single break statement.

Why should we avoid goto statement in C?

NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify.

What can I use instead of goto in C?

It is good programming style to use the break , continue , and return statements instead of the goto statement whenever possible. However, because the break statement exits from only one level of a loop, you might have to use a goto statement to exit a deeply nested loop.

What is goto statement in C with example?

The use of goto statement may lead to code that is buggy and hard to follow. For example, one: for (i = 0; i < number; ++i) { test += i; goto two; } two: if (test > 5) { goto three; } ... .. ... Also, the goto statement allows you to do bad stuff such as jump out of the scope.


1 Answers

This is so called Labels as Values and represents one of the GCC extensions.


As an example, I've applied this extension to give an answer to Printing 1 to 1000 without loop or conditionals question:

void printMe () 
{
    int i = 1;
    startPrintMe:
    printf ("%d\n", i);
    void *labelPtr = &&startPrintMe + (&&exitPrintMe - &&startPrintMe) * (i++ / 1000);
    goto *labelPtr;
    exitPrintMe:
}
like image 118
Martin Babacaev Avatar answered Nov 06 '22 22:11

Martin Babacaev