Labels As Values; Nested Functions - Red Hat ENTERPRISE LINUX 3 - USING GCC Using Instructions

Using the gnu compiler collection (gcc)
Hide thumbs Also See for ENTERPRISE LINUX 3 - USING GCC:
Table of Contents

Advertisement

Chapter 6. Extensions to the C Language Family
123

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
. This value is a constant and can be used wherever a
&&
void *
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 state-
1
ment
,
. For example,
goto *
;
exp
goto *ptr;
Any expression of type
is allowed.
void *
One way of using these constants is in initializing a static array that will serve 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
statement. The
switch
switch
statement is cleaner, so use that rather than an array unless the problem does not fit a
statement
switch
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 unpre-
dictable things will 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.

6.4. Nested Functions

A nested function is a function defined inside another function. (Nested functions are not supported
for GNU C++.) The nested function's name is local to the block where it is defined. For example, here
we define a nested function named
, and call it twice:
square
foo (double a, double b)
{
double square (double z) { return z * z; }
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.

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the ENTERPRISE LINUX 3 - USING GCC and is the answer not in the manual?

Questions and answers

This manual is also suitable for:

Enterprise linux 3

Table of Contents