Category: Local labels

Local labels in C Programming

Introduction

Everybody who has programmed in C must be knowing about “goto” and “labels“.
In GCC, there is something called local labels which restrict the scope of label and do cool stuff.
Linux kernel internal APIs extensively use local labels.

Comparison between Labels and Local Labels

Conventional labels in gcc have function scope. Where as local label can be scoped to a nested block.
Conventional Labels cannot be declared more than once in a function and that is where
local labels are used.

In complex function implementations, program often want to jump to an instruction and handle each jump
differently for different cases. In such cases local labels could be a good choice.

Example Code

Macro with local label
Macro without local label declared

Now if u call “MACRO_WITH_LOCAL_LABEL()” from any function it won’t give any compilation errors

where as calling “MACRO_WITHOUT_LOCAL_LABEL()” would give following error


[root@blr-1st-1-dhcp446 3. gcc_local_labels]# gcc -c try.c
try.c: In function ‘main’:
try.c:63: error: duplicate label ‘not_empty’
try.c:53: note: previous definition of ‘not_empty’ was here
try.c:63: error: duplicate label ‘empty’
try.c:53: note: previous definition of ‘empty’ was here
try.c:63: error: duplicate label ‘exit’
try.c:53: note: previous definition of ‘exit’ was here

Pre-processor stage successfully completes but compilation stage gives error.

Existing example

As mentioned earlier in the post, Linux code uses it these techniques in debug codes to keep track of instruction pointers etc.
For instance check usage of following macros in the code :

#define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })

Many internal APIs of linux kernel like kmalloc() etc. call this macro to track caller function address.
Now what is this “&&__here” ? Just in brief, this is address of label, which you can store in pointers. COOL ! Isn’t ?

Advertisements