User Tools

Site Tools


blog:2025-07-07-001



2025-07-07 C: 模擬 nameof() & typeof()

  • 在 C 語言中,沒有直接對應於 C# 的 nameof() 和 typeof() 的功能,因為 C 是一種靜態類型語言,且不支持反射或類似的運行時類型查詢機制。不過,可以使用一些技巧來模擬這些功能。

模擬 nameof()

  • 在 C 語言中,沒有內建的 nameof() 功能,但可以通過宏來達成類似的效果:
  • #include <stdio.h>
    
    #define nameof(var) #var
    
    int main() {
        int myVariable = 42;
        printf("The name of the variable is: %s\n", nameof(myVariable)); // 輸出: The name of the variable is: myVariable
        return 0;
    }
  • 說明:
    • 使用 # 運算符將變量名稱轉換為字符串,這樣在調用 nameof(myVariable) 時,會返回 “myVariable”。

模擬 typeof()

  • C 語言中也沒有 typeof(),但是可以使用 sizeof 來獲取變量的大小,並通過宏來模擬類似的行為:
  • #include <stdio.h>
    
    #define typeof(var) _Generic((var), \
        int: "int", \
        float: "float", \
        double: "double", \
        char: "char", \
        default: "unknown type" \
    )
    
    int main() {
        int myInt;
        float myFloat;
    
        printf("The type of myInt is: %s\n", typeof(myInt));   // 輸出: The type of myInt is: int
        printf("The type of myFloat is: %s\n", typeof(myFloat)); // 輸出: The type of myFloat is: float
    
        return 0;
    }
  • 說明:
    • _Generic 是 C11 引入的一個特性,可以根據表達式的類型選擇對應的字符串。
    • 當傳入不同類型的變量時,會返回相應的類型名稱字符串。

注意事項

  • 這些模擬功能並不能完全替代 C# 中的 nameof() 和 typeof()
  • 因為 C 語言的靜態性和簡單性使得這些功能的實現受到限制。
  • sizeof 和 _Generic 只能用於編譯時已知的類型。

TAGS

  • 1 person(s) visited this page until now.

blog/2025-07-07-001.txt · Last modified: 2025/07/07 09:21 by jethro