定义不评估 POD?
我正在在线查看 C++ FAQ Lite。我再次浏览内联,因为我还没有找到它们的用途,并且想知道如何停止循环依赖,如 这个答案。我首先尝试做“为什么内联比定义更好”。具有以下代码的示例:
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )
inline
int safe(int i)
{
return i >= 0 ? i : -(i);
}
int f();
int main(void)
{
int x(5);
int ans;
ans = unsafe(x++);
cout << ans << endl;
ans = unsafe(++x);
cout << ans << endl;
ans = safe(x++);
cout << ans << endl;
ans = safe(++x);
cout << ans << endl;
std::cin.get();
return 0;
}
编辑:
太棒了。解决了拼写错误。并不是说我因为没有发现这样的错误或任何东西而感到痛苦。
现在输出为 6, 9, 9, 11
。
然而,即使预自增,第一个值不应该结果为 7 吗?
如果宏被调用两次,那么它不是像这样:
unsafe(x) // 预递增在调用时不会修改值。
unsafe(++x) // 出于所有意图和目的,增量发生在第二次调用之前,因此 ++x.这是针对第一个 ans = unsafe(x++)
(如果它被调用两次的话)。
当我们到达第二个 ans = unsafe(++x)
时,x 不应该增加两次吗?一次是通过双重调用,一次是在第一次双重调用完成时?
I was going over the C++ FAQ Lite online. I was browsing inlines again since I haven't found a use for them and wanted to know how the stopped the circular dependency as showed in this answer. I first tried to do the, "Why inlines are better than defines." example with the following code:
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )
inline
int safe(int i)
{
return i >= 0 ? i : -(i);
}
int f();
int main(void)
{
int x(5);
int ans;
ans = unsafe(x++);
cout << ans << endl;
ans = unsafe(++x);
cout << ans << endl;
ans = safe(x++);
cout << ans << endl;
ans = safe(++x);
cout << ans << endl;
std::cin.get();
return 0;
}
EDIT:
Great. Got the typo out of the way. Not that I'm bitter that I don't find such errors or anything.
The output is now 6, 9, 9, 11
.
However, even with pre-incrementation, shouldn't the first value result in 7?
If the macro is being called twice, then doesn't it go like this:
unsafe(x) // pre-incrementation doesn't modify the value when called.
unsafe(++x) // for all intents and purposes, the incrementation happens before the second call, so the ++x. This is for the first ans = unsafe(x++)
if it's being called twice.
By the time we reach the second ans = unsafe(++x)
, shouldn't the x have been incremented twice? Once by the double call and once when the first double call was finished?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而不是:
我认为您想要:
响应您的编辑:
在第一次调用
unsafe(x++)
后,x
是 7,即使ans< /code> 是 6。这是因为您有这样的语句:
ans
被分配给最左边的之后的中间
被评估。结果是,x++
x++ans == 6
但x == 7
。与unsafe(++x)
的区别在于,ans
被赋值给++x
,意味着结果是ans == x == 9 。
Instead of:
I think you want:
In response to your edit:
After the first call to
unsafe(x++)
,x
is 7, even though theans
is 6. This is because you have the statement:ans
is assigned to the middlex++
after the left-mostx++
is evaluated. As a result,ans == 6
butx == 7
. The difference withunsafe(++x)
is thatans
is assigned to++x
, meaning the result isans == x == 9
.