This shows you the differences between two versions of the page.
— |
blog:2025-07-07-001 [2025/07/07 09:21] (current) jethro created |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ~~NOTOC~~ | ||
+ | ====== 2025-07-07 C: 模擬 nameof() & typeof() ====== | ||
+ | * 在 C 語言中,沒有直接對應於 C# 的 nameof() 和 typeof() 的功能,因為 C 是一種靜態類型語言,且不支持反射或類似的運行時類型查詢機制。不過,可以使用一些技巧來模擬這些功能。 | ||
+ | ===== 模擬 nameof() ===== | ||
+ | * 在 C 語言中,沒有內建的 nameof() 功能,但可以通過宏來達成類似的效果: | ||
+ | * <sxh c>#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; | ||
+ | }</sxh> | ||
+ | * 說明: | ||
+ | * 使用 # 運算符將變量名稱轉換為字符串,這樣在調用 nameof(myVariable) 時,會返回 "myVariable"。 | ||
+ | ===== 模擬 typeof() ===== | ||
+ | * C 語言中也沒有 typeof(),但是可以使用 sizeof 來獲取變量的大小,並通過宏來模擬類似的行為: | ||
+ | * <sxh c>#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; | ||
+ | }</sxh> | ||
+ | * 說明: | ||
+ | * _Generic 是 C11 引入的一個特性,可以根據表達式的類型選擇對應的字符串。 | ||
+ | * 當傳入不同類型的變量時,會返回相應的類型名稱字符串。 | ||
+ | ===== 注意事項 ===== | ||
+ | * 這些模擬功能並不能完全替代 C# 中的 nameof() 和 typeof() | ||
+ | * 因為 C 語言的靜態性和簡單性使得這些功能的實現受到限制。 | ||
+ | * sizeof 和 _Generic 只能用於編譯時已知的類型。 | ||
+ | ===== TAGS ===== | ||
+ | * | ||
+ | ====== ====== | ||
+ | * {{counter}} person(s) visited this page until now. | ||
+ | * [[:memo:index|Back]] | ||
+ | ====== ====== | ||
+ | <html><!-- | ||
+ | PDF for A4-Portrait: {{pdfjs 50%,450px > xxx.pdf?page-fit}} | ||
+ | PDF for A4-Landscape: {{pdfjs 500px,700px > xxx.pdf?page-fit}} | ||
+ | PDF for iPad Note: {{pdfjs 700px,500px > xxx.pdf?page-fit}} | ||
+ | |||
+ | Youtube: {{youtube>large:XXXXX}} | ||
+ | Code Highlight: <sxh php; first-line: 70; highlight: [89,92]; title: New title attribute in action> | ||
+ | |||
+ | --></html> | ||