首页  >  文章  >  后端开发  >  在C语言中,预定义标识符__func__

在C语言中,预定义标识符__func__

王林
王林转载
2023-08-30 12:49:06745浏览

在C语言中,预定义标识符__func__

标识符是在编程中给实体赋予的名称,以在程序中进行标识。

通常,标识符是由程序员创建的,以实现高效工作,但也有一些预定义的标识符内置在编程中。例如,cout、cin等。

在这里,我们将看到C编程语言中的一个预定义标识符__func__。

__func__的正式定义为 −

“标识符__func__应被翻译器隐式声明,就好像在每个函数定义的左花括号之后立即跟着声明一样。”

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</p><p>", __func__);
}
void function2 (void){
   printf ("%s</p><p>", __func__);
   function1 ();
}
int main (){
   function2 ();
   return 0;
}

输出

function2
function1

Explanation − 在这里,我们使用了__func__方法来返回被调用的函数的名称。标识符返回它被调用的函数的名称。两个print语句都调用了__func__来获取自己的方法引用。

这个标识符甚至可以在主方法中使用。例如,

示例

 在线演示

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

输出

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</p><p>", __func__);
   return 0;
}

输出

error

还有其他类似的功能在C编程语言中也可以进行类似的识别工作。其中一些是

__File__ - 返回当前文件的名称。

__LINE__ - 返回当前行的编号。

让我们看一个代码来展示实现

示例

 在线演示

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

输出

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

Explanation − 这些是一些通用函数,可能在我们收集有关文件名、代码行和当前调用的函数的信息时会有用,使用__func__,__LINE__,__FILE__标识符。

以上是在C语言中,预定义标识符__func__的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除