[英]Using macro to concatenate
抱歉,我錯過了分號,我現在添加了。
#include <stdio.h>
#define m(i,j) (i##j)
int main(){
m(hello,world);
return 0;
}
編譯時出現以下錯誤 main.c:在函數main中:main.c:8:1:錯誤:未聲明“ helloworld”(此功能首次使用)main.c:8:1:注意:每個未聲明的標識符對於出現在其中的每個功能僅報告一次
但
#include <stdio.h>
#define m(i,j) (i##j)
int main(){
m(1,2);
return 0;
}
完美地工作,並給出答案為12
您必須記住,預處理程序實際上是替換了宏調用。 因此,在您的情況下,宏調用
m(hello,world)
變
(helloworld)
那不是C語言中的有效語句或表達式。您詢問的錯誤是因為編譯器不知道helloworld
是什么,但是由於缺少分號,還應該存在其他錯誤。
另一個示例至少用(12)
代替m(1,2)
,因為沒有未聲明的標識符,因此更有效。 但是它仍然缺少分號。
應用宏后,您將得到以下信息:
#include <stdio.h>
int main(){
(helloworld)
return 0;
}
編譯器在說, helloworld
是什么?
看一下這個
#include <stdio.h>
#define m(i,j) (i##j)
int main(){
m('hello','world')
return 0;
}
當您使用宏將hello和world連接在一起時,實際上並沒有創建char *或char [], 而是創建了一個符號。
因為代碼helloworld
之前沒有在代碼中定義,所以您當然會得到未定義的錯誤。 要解決此問題,您可以簡單地將符號定義為int或任何其他原語,並將其聲明放在宏之前:
int helloworld;
接着
m(hello,world) = 10;
printf ("%d", helloworld);
您可以通過將字符串彼此相鄰來串聯它們。
#include <stdio.h>
#define m(i,j) (i j)
int main(){
m("hello","world");
return 0;
}
要不就
int main(){
"hello" "world";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.