我有一个奇怪的愿望;我不知道那里是否有任何编译器或语言扩展允许这样做。
我希望能够在函数调用中声明变量,如下所示:
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 的作用域。再举一个例子(来 self 现在正在做的一个项目),我有
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) {
...
}
}
或类似的东西。
最佳答案
除了 block 作用域声明之外,在 C99 中,基本上还有两种其他方法来声明根据定义仅限于它们出现的语句的变量:
- 复合文字的形式为
(type name){ initializers }
并声明一个存在于当前 block 中的局部变量。例如,对于函数调用,您可以使用test(&(int){ 0 })
。 for
范围变量仅具有for
语句本身和依赖语句或 block 的范围。
你的 if
表达式与局部变量你可以做一些奇怪的事情,比如
for (bool cntrl = true; cntrl; cntrl = false)
for (int ret = something; cntrl && test(&ret); cntrl = false) {
// use ret inside here
}
小心,这样的东西很快就变得不可读了。另一方面,优化器非常有效地将此类代码缩减为基本代码,并且很容易发现 test
和 for
block 的内部仅被评估一次。
关于c - 在 C 函数的参数中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9463277/