[英]C: evaluate 2 expressions in order and then return the first
有沒有更簡潔的方法來重寫以下 function 而不會犧牲清晰度?
function uint64_t pop_int(uint8_t** p, int num_bytes)
{
uint64_t res = decode_int(*p, num_bytes);
*p += num_bytes;
return res;
}
我能想到的只是
return decode_int((*p += num_bytes) - num_bytes, num_bytes);
但如果該語言有類似FIRST
function 之類的東西,您可以像這樣使用它會更清楚:
return FIRST(decode_int(*p, num_bytes), *p += num_bytes);
但必須清楚的是,arguments 是按順序評估的。
在 C 中,您編寫的是用於解決任務的慣用代碼。
在帶有 try-finally 的語言中,您可以使用它,它可能會或可能不會更清楚。 但是 C 沒有這個功能。
終於找到了...我需要的語法是({... ; expr})
(在 linux 內核的 CIRC_SPACE_TO_END 宏中使用)。 對於我的例子,我需要的是:
#define POST_INC(type, a, b) ({type* tmp = a; a += b; tmp;})
示例用法:
int main()
{
char const* str = "hello, world";
printf("%s\n", POST_INC(char const, str, 5));
printf("%s\n", POST_INC(char const, str, 2));
printf("%s\n", POST_INC(char const, str, 5));
}
結果:
hello, world
, world
world
我很高興我沒有放棄!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.