问题描述
假设我想编写一个从x到y的简单循环,每次循环运行时,x都会增加1.
这是代码我试过了。
Say I want to write a simple loop that goes from x to y and every time this loop runs, x gets incremented by 1.
This is the code I've tried.
#define LOOP(x,y) while(x<=y)\
{\
printf("%d", x);\
x++;\
}
但这会在x ++行给出一个错误,说 [错误]左值作为递增操作数。
同样的错误即使我用++ x替换x ++,x = x + 1,x + = 1,也会出现。 使用宏编写函数时递增变量的正确方法是什么?
我尝试过:
But this gives an error at the x++ line saying "[Error] lvalue required as increment operand".
The same error appears even if I replaced x++ with ++x, x=x+1, x+=1. What is the correct way of incrementing a variable when writing a function using macros?
What I have tried:
#define LOOP(x,y) while(x<=y)\
{\
printf("%d", x);\
x++;\
}
<pre>#define LOOP(x,y) while(x<=y)\
{\
printf("%d", x);\
++x;\
}
<pre>#define LOOP(x,y) while(x<=y)\
{\
printf("%d", x);\
x=x+1;\
}
<pre>#define LOOP(x,y) while(x<=y)\
{\
printf("%d", x);\
x+=1;\
}
推荐答案
LOOP(1,3);
这是行不通的,因为文字 1
和 3
不是左值。
只需像预处理器那样扩展代码:
That won't work because the literals 1
and 3
are not lvalues.
Just expand the code as done by the preprocessor:
while(1<=3)
{
printf("%d", 1);
// This is not allowed!
// The left side must be an lvalue
1++;
}
完全避免使用这些宏。它们容易产生不良副作用。例如:
Avoid such macros at all. They are prone to unwanted side effects. An example:
int x = 1;
int y = 3;
LOOP(x--, ++y);
虽然上面的编译没有错误,但未定义会发生什么,并且您将使用不同的编译器执行不同数量的循环。 br />
解决方案是在使用最新的C编译器时使用内联函数:
While the above would compile without errors, it is undefined what happens and you will have a different number of loops executed with different compilers.
The solution is to use inline functions when using a recent C compiler:
static inline void loop(int x, int y)
{
while (x<=y)
{
printf("%d", x);
x++;
}
}
然而,这只允许传递 int
(具有类型检查的优势)并且可能被编译器忽略(他仍然可以创建并调用该函数)。
However, this allows only int
s to be passed (with the advantage of type checking) and may be ignored by the compiler (he may still create and call the function).
LOOP(1, 7)
评估为
which evaluates to
while(1 <= 7)
{
printf("%d", 1);
1++;
}
这种情况永远不会奏效。 x
字段必须是左值,即可以更改的非常量数字变量。
And that can never work. The x
field must be an lvalue, i.e. a non-const numeric variable that can be changed.
这篇关于如何在使用C预处理器宏时增加变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!