C/C++ 赋值运算符实现的底层细节.它返回什么? [英] Low level details of C/C++ assignment operator implementation. What does it return?

查看:37
本文介绍了C/C++ 赋值运算符实现的底层细节.它返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C++ 世界(还有 C)的新手.并且不知道它的所有细节.但有一件事真的让我很困扰.它是这样的结构:while (a=b) {...} .据我所知,这个魔法是有效的,因为 C 和 C++ 中的赋值运算符会返回一些东西.那么问题来了:它返回什么?这是记录在案的事情吗?它在 C 和 C++ 中的工作方式是否相同.非常感谢有关赋值运算符及其在 C 和 C++ 中的实现(如果有差异)的低级详细信息!

我希望这个问题不会被关闭,因为我无法从低级的角度找到关于这个主题的全面解释和好的材料.

I m a total newbie to a C++ world (and C too). And don't know all its details. But one thing really bothers me. It is constructions like : while (a=b) {...} .As I understand this magic works because assignment operator in C and C++ returns something. So the questions: what does it return? Is this a documented thing?Does it work the same in C and C++. Low level details about assignment operator and its implementation in both C and C++ (if there is a difference) will be very appreciated!

I hope that this question won't be closed, because I can't find a comprehensive explanation and good material on this theme from the low level point of view all the more so.

推荐答案

对于 C++ 中的内置类型,对赋值表达式求值会产生一个左值,它是赋值表达式的左侧.赋值在结果可用之前进行排序,因此当结果转换为右值时,您将获得新分配的值:

For built-in types in C++ evaluating an assignment expression produces an lvalue that is the left hand side of the assignment expression. The assignment is sequenced before the result can be used, so when the result is converted to an rvalue you get the newly assigned value:

int a, b=5;
int &c = (a=b);
assert(&c==&a);
b=10;
assert(10==(a=b));

C 几乎但不完全相同.C 中赋值表达式的结果是一个与新分配给赋值左侧的值相同的右值.

C is almost but not exactly the same. The result of an assignment expression in C is an rvalue the same as the value newly assigned to the left hand side of the assignment.

int *c = &(a=b); // not legal in C because you can only take the address of lvalues.

通常,如果完全使用赋值的结果,则将其用作右值(例如,a=b=c),因此 C++ 和 C 之间的这种差异在很大程度上不会引起注意.

Usually if the result of an assignment is used at all it's used as an rvalue (e.g., a=b=c), so this difference between C++ and C largely goes unnoticed.

这篇关于C/C++ 赋值运算符实现的底层细节.它返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆