我有一种奇怪的愿望;我不知道是否有任何编译器或语言扩展允许这样做。
我希望能够在函数调用中声明变量,如下所示:
int test(int *out_p) {
*out_p = 5;
return 1;
}
int main()
{
if (int ret = test(int &var)) { // int var declared inside function invocation
fprintf(stderr, "var = %d\n", var); // var in scope here
}
return 0;
}
因为 var 的作用域遵循 ret 的作用域。再举一个例子(来自我现在正在做的一个项目),我有
cmd_s = readline();
int x, y, dX, dY, symA, symB;
if (sscanf(cmd_s, "placeDomino:%d %d atX:%d y:%d dX:%d dY:%d",
&symA, &symB, &x, &y, &dX, &dY) == 6) {
do_complicated_stuff(symA, symB, x, y, dX, dY);
} else if (sscanf(cmd_s, "placeAtX:%d y:%d dX:%d dY:%d", &x, &y, &dX, &dY) == 4) {
do_stuff(x, y, dX, dY);
/* symA, symB are in scope but uninitialized :-( so I can accidentally
* use their values and the compiler will let me */
}
我更愿意写
cmd_s = readline();
if (sscanf(cmd_s, "placeDomino:%d %d atX:%d y:%d dX:%d dY:%d",
int &symA, int &symB, int &x, int &y, int &dX, int &dY) == 6) {
do_complicated_stuff(symA, symB, x, y, dX, dY);
} else if (sscanf(cmd_s, "placeAtX:%d y:%d dX:%d dY:%d", int &x, int &y, int &dX, int &dY) == 4) {
do_stuff(x, y, dX, dY);
/* Now symA, symB are out of scope here and I can't
* accidentally use their uninitialized values */
}
我的问题是,有没有编译器支持这个?如果我以正确的方式摩擦它,gcc 是否支持它?是否有具有此功能的 C 或 C++(草案)规范?
编辑:刚刚意识到在我的第一个代码示例中,我的 int ret 声明在 C99 中也不好;我想我被 for 循环宠坏了。我也想要那个功能;想象
while(int condition = check_condition()) {
switch(condition) {
...
}
}
或类似的东西。