[問題] 小括號裡面包一個block(linux kernel的container_of)

看板C_and_CPP (C/C++)作者時間12年前 (2013/11/01 10:03), 編輯推噓0(007)
留言7則, 3人參與, 最新討論串1/1
linux kernel裡有一個macro 叫container_of 他的用途是當你有一個struct member的指標時 你可以用他來取得擁有這個member的struct之指標 研究完以後對於他實作的原理我是瞭解 不過看完後確定裡面的語法有一些疑惑 定義如下 #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) 他的用法大概是這樣子 struct my_struct { type1 member1; type2 member2; } type2* a = getType(); struct s* = container_of(a, struct my_struct, member2); // line 1 container_of可以把他簡化成這樣的形式 ({expression 1;expression 2;) 把它展開後, 上面的line 1會變成下面的形式 struct s* = ({expression 1;expression 2;}); 我有點看不懂為何可以這樣寫 不知道這種小括號裡面包一個block的語法是什麼 懇請各位先進賜教 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.56.235.142 ※ 編輯: eai 來自: 61.56.235.142 (11/01 10:04)

11/01 10:26, , 2F
感謝你~~順便想請教一下這是GNU C專屬的語法嗎?? 手邊沒有其他
11/01 10:26, 2F

11/01 10:26, , 3F
的compiler可以驗證
11/01 10:26, 3F

11/01 11:13, , 4F
是的, 上面的個網頁是在 GCC 的 "C extensions" 這章底下
11/01 11:13, 4F

11/01 12:44, , 5F
不使用這個extension也是可以定義出offsetof()的
11/01 12:44, 5F

11/01 12:45, , 6F
抱歉我弄錯本文重點了 :D
11/01 12:45, 6F

11/01 20:43, , 7F
scwg大大謝謝你~~
11/01 20:43, 7F
文章代碼(AID): #1ISmlUiZ (C_and_CPP)
文章代碼(AID): #1ISmlUiZ (C_and_CPP)