Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Predefined Identifier __func__ ใน C


Identifier คือชื่อที่ให้กับ entity ในโปรแกรมมิ่งเพื่อระบุตัวตนในโปรแกรม

โดยทั่วไป identifiers ถูกสร้างโดยโปรแกรมเมอร์ แต่มี predefined identifiers ที่ built-in อยู่ เช่น cout, cin เป็นต้น

ที่นี่ เราจะดู predefined identifier หนึ่งของ C programming language คือ __func__

นิยามทางการของ __func__ คือ −

"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 __func__ เป็น compiler-generated identifier ที่สร้างขึ้นเพื่อระบุฟังก์ชันโดยใช้ชื่อฟังก์ชัน

มาดูตัวอย่างโค้ดเพื่อให้เข้าใจชัดเจนขึ้น

ตัวอย่าง

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

ผลลัพธ์

function2
function1

Explanation − ที่นี่ เราใช้ __func__ method เพื่อคืนชื่อฟังก์ชันที่ถูกเรียก Identifier คืนชื่อฟังก์ชันที่มันถูก invoke ไป ทั้งสอง print statements เรียก __func__ สำหรับ method reference ของตัวเอง

Identifier นี้ทำงานได้กับ main method ด้วย ตัวอย่าง

ตัวอย่าง

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

ผลลัพธ์

main

แต่ไม่สามารถ overwrite ได้ คือ __func__ reserved สำหรับ function names เท่านั้น การใช้เก็บอย่างอื่นจะ error

มาดู

ตัวอย่าง

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

ผลลัพธ์

error

มีฟังก์ชันคล้ายๆ กันอีกใน C เช่น

__File__ − คืนชื่อไฟล์ปัจจุบัน

__LINE__ − คืนหมายเลขบรรทัดปัจจุบัน

มาดูโค้ดแสดงการนำไปใช้

ตัวอย่าง

#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;
}

ผลลัพธ์

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

Explanation − นี่คือฟังก์ชันทั่วไปที่อาจมีประโยชน์ เราเก็บข้อมูล filename, line of code, และ function ที่ invoke อยู่ ด้วย __func__,__LINE__,__FILE__ identifiers