Predefined Identifier __func__ in C


Identifier is the name given to an entity in programming to identify it in the program.

Generally, identifiers are created by the programmer for efficient working but there are some predefined identifiers that are inbuilt in programming. For example, cout, cin, etc.

Here, we will see one of these predefined identifiers of C programming language which is __func__.

The formal definition of __func__ is  −

“The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration

static const char __func__[] = “function-name”;

appeared, where function-name is the name of the lexically-enclosing function.”

C program The __func__ is a compiler-generated identifier that is created to identify the function using function name.

Let’s see a few code examples to make the concept more clear,

Example

 Live Demo

#include <stdio.h>
void function1 (void){
   printf ("%s\n", __func__);
}
void function2 (void){
   printf ("%s\n", __func__);
   function1 ();
}
int main (){
   function2 ();
   return 0;
}

Output

function2
function1

Explanation − Here, we have used the __func__ method to return the names of the functions that are called. The identifier returns the name of the function in which it is invoked. Both the print statements called for the __func__ for its own method reference.

This identified works on even the main method. Example,

Example

 Live Demo

#include <stdio.h>
int main (){
   printf ("%s\n", __func__);
   return 0;
}

Output

main

But this cannot be overwritten i.e. __func__ is reserved for function names only. Using it to store anything else will return error.

Let’s see

Example

 Live Demo

#include <stdio.h>
int __func__ = 123;
int main (){
   printf ("%s\n", __func__);
   return 0;
}

Output

error

There are other similar functions too in C programming language which do similar work of identification. Some are

__File__ − return the name of the current file.

__LINE__ − returns the number of current line.

Lets see a code to show the implementation

Example

 Live Demo

#include <stdio.h>
void function1(){
   printf("The function: %s is in line: %d of the file :%s\n", __func__,__LINE__,__FILE__);
}
int main(){
   function1();
   return 0;
}

Output

The function: function1 is in line: 3 of the file :main.c

Explanation − these are some general functions that might be useful as we have gathered information regard filename, line of code and function that is currently invoked using the __func__,__LINE__,__FILE__ identifiers.

raja
Published on 04-Feb-2020 07:25:57
Advertisements