我有一个有点奇怪的愿望,不知道是否有任何编译器或语言扩展可以实现。
我想能够在函数调用内部声明变量,就像这样:
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;
}
因此,变量的作用域遵循 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 */
}
and I would prefer to write
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) {
...
}
}
或者类似的东西。