是否可以在C++的for循环的初始化主体中声明两个不同类型的变量?
例如:
for(int i=0,j=0 ...
Run Code Online (Sandbox Code Playgroud)
定义了两个整数.我可以在初始化主体中定义a int和a char吗?怎么做?
不幸的是,在C中没有任何智能指针..但是有可能构建一个宏来包装变量声明并在离开声明变量的范围时使用该变量作为输入变量调用函数调用吗?
很抱歉这个长短语,但我正在使用xnu内核,你有许多内置引用计数器的元素,并且一定不要忘记在使用它时不用这个元素来避免内存泄漏.
例如,如果我有以下类型proc_t:
struct proc;
typedef struct proc * proc_t;
Run Code Online (Sandbox Code Playgroud)
我想在范围内基于此类型声明堆栈变量,例如:
{
proc_t_release_upon_exit proc_t proc_iter = proc_find(mypid);
//the rest of the code in this scope
}
Run Code Online (Sandbox Code Playgroud)
在预处理器分析宏之后和编译之前,我希望生成以下代码:
{
proc_t myproc = proc_find(mypid)
//the rest of the code in scope
proc_rele(myproc);
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在C中定义这样的宏?
为什么这不起作用
for( int i = 0, int x = 0; some condition; ++i, ++x )
Run Code Online (Sandbox Code Playgroud)
这是
int i, x;
for( i = 0, x = 0; some condition; ++i, ++x )
Run Code Online (Sandbox Code Playgroud)
谢谢
或者,"在for循环中声明多个变量是禁止的"?
我的原始代码是
for( int i = 1, int i2 = 1;
i2 < mid;
i++, i2 = i * i ) {
Run Code Online (Sandbox Code Playgroud)
我想循环通过第一个这么多的正方形,并且想要数字和它的正方形,并且停止条件取决于正方形.这段代码似乎是意图的最干净的表达,但它无效.我可以想到十几种解决这个问题的方法,所以我不是在寻找最好的选择,而是为了更深入地理解为什么这是无效的.一点语言律师,如果你愿意的话.
我已经足够记住你必须在函数开始时声明所有变量,所以我很感激
for( int i = 0; ....
Run Code Online (Sandbox Code Playgroud)
句法.阅读它看起来好像你只能在for()语句的第一部分中有一个类型声明.所以你可以做到
for( int i=0, j=0; ...
Run Code Online (Sandbox Code Playgroud)
甚至略有巴洛克风格
for( int i=0, *j=&i; ...
Run Code Online (Sandbox Code Playgroud)
但不是我明智的
for( int i=0, double x=0.0; ...
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么?这是for()的限制吗?或者对逗号列表的限制,比如"逗号列表的第一个元素可以声明一个类型,但不能声明另一个?"下面使用逗号来区分C++的不同语法元素吗?
(一个)
for( int i=0, j=0; ...
Run Code Online (Sandbox Code Playgroud)
(B)
int i = 0, j = 0;
Run Code Online (Sandbox Code Playgroud)
(C)
int z;
z = 1, 3, 4;
Run Code Online (Sandbox Code Playgroud)
那里有专家吗?
根据我得到的好反应,我想我可以提出这个问题:
在for语句中
for( X; Y; …Run Code Online (Sandbox Code Playgroud) 我想在if语句的括号中声明一个局部变量.例如.
if((char c = getc(stdin)) == 0x01)//This is not OK with g++.
{
ungetc(c, stdin);
}
Run Code Online (Sandbox Code Playgroud)
我想要的是,看看角色是否是我想要的角色.常用说了吧,我想用变量(焦三)双方在行,如果和身体如果,但是没有外界如果.
但是g ++(GCC 4.8.1)说'char'之前的预期主表达式.我想知道是否有办法做到这一点,因为我不想要类似的东西
char c = getc(stdin);
if(c == 0x01)
{
bla...
}
Run Code Online (Sandbox Code Playgroud) 虽然风格不好,但在parens中有一个带有支撑的for循环是合法的吗?像这样:
char *a = "a ";
char *b = "b ";
for ( { int aComesFirst = 1;
char *first = a;
char *second = b;
};
aComesFirst >= 0;
{ aComesFirst--;
swap(first, second);
} )
{
printf("%s%s\n", first, second);
}
Run Code Online (Sandbox Code Playgroud)
如果有可能出现这些问题,我应该在第一次关闭括号之后加一个分号,还是会添加一个空语句?
我确实认识到,char*在for循环之外移动声明以及循环swap内部结束时,在风格上更好.但风格不是这个问题的重点,我只是想知道是否可以在支架内放置支架.
c++ ×4
for-loop ×3
c ×2
c++11 ×1
curly-braces ×1
declaration ×1
loops ×1
macros ×1
scope ×1
variables ×1