文字字符串和函数返回值是左值还是右值?

发布于 2024-08-17 13:20:31 字数 125 浏览 7 评论 0原文

  1. 只是想知道文字字符串是左值还是右值。其他文字(如 int、float、char 等)是左值还是右值?

  2. 函数的返回值是左值还是右值?

你如何区分?

  1. Just wonder if a literal string is an lvalue or an rvalue. Are other literals (like int, float, char etc) lvalue or rvalue?

  2. Is the return value of a function an lvalue or rvalue?

How do you tell the difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情仇皆在手 2024-08-24 13:20:32

C语言中有两种表达式:
1. 左值:作为左值的表达式可以出现在赋值的左侧或右侧。
2. 右值:作为右值的表达式可以出现在赋值的右侧,但不能出现在左侧。
变量是左值,因此可能出现在赋值的左侧。数字文字是右值,因此不能被赋值,也不能出现在左侧。以下是有效的声明:
整数 g = 20;
但以下不是有效的语句,会生成编译时错误:
10=20;

There are two kinds of expressions in C:
1. lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
2. rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and cannot appear on the left-hand side. Following is a valid statement:
int g = 20;
But following is not a valid statement and would generate compile-time error:
10=20;

是你 2024-08-24 13:20:32

Microsoft 有一个针对 C++ 的定义。根据这个定义,
一个文字字符串,比如“hello world”,是左值,因为它是 const 并且不是临时的。实际上它会在应用程序的整个生命周期中持续存在。

there's a definition for C++ from Microsoft. By this definition,
a literal string, say "hello world", is lvalue, because it's const and not temporary. Actually it persists across your application's lifetime.

此刻的回忆 2024-08-24 13:20:31
  1. 字符串文字是左值,但您不能更改它们
  2. 右值,但如果它是指针且非 NULL,则它指向的对象是左值

C 标准识别代表 left 的原始术语L = R;然而,它说将左值视为定位器值,这大致意味着您可以获得对象的地址,因此该对象有一个位置。 C99 中的 6.3.2.1。)

(参见 同样的道理,标准已经放弃了术语右值,而只使用“表达式的值”,这实际上是所有内容,包括诸如整数、字符、浮点数等文字。此外,您可以使用右值执行的任何操作都可以也使用左值完成,因此您可以将所有左值视为右值。

  1. string literals are lvalues, but you can't change them
  2. rvalue, but if it's a pointer and non-NULL, the object it points to is an lvalue

The C standard recognizes the original terms stood for left and right as in L = R; however, it says to think of lvalue as locator value, which roughly means you can get the address of an object and therefore that object has a location. (See 6.3.2.1 in C99.)

By the same token, the standard has abandoned the term rvalue, and just uses "the value of an expression", which is practically everything, including literals such as ints, chars, floats, etc. Additionally, anything you can do with an rvalue can be done with an lvalue too, so you can think of all lvalues as being rvalues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文