1

enter image description here

Indicate in cppreference that the expression representing the subscript must be a prvalue of unscoped enumeration or integral type.

So why can a for loop that traverses a built-in array, which beginners have learned, be compiled.

such as:

int a[10] = {0};
// as we know ,i is a lvalue
for(int i = 0; i < 10; i++)
{
    std::cout << a[i] << std:endl;
}
LandP
  • 173
  • 6
  • Why *not?* Do you have something against variables as indices? – user207421 Apr 21 '22 at 07:50
  • 2
    An lvalue can be converted (implicitly) to an rvalue. – Adrian Mole Apr 21 '22 at 07:54
  • 1
    There is [implicit conversion](https://en.cppreference.com/w/cpp/language/implicit_conversion#Value_transformations). – Jarod42 Apr 21 '22 at 07:54
  • Is [this](https://stackoverflow.com/q/3601602/10871073) a duplicate? – Adrian Mole Apr 21 '22 at 07:55
  • Does this answer your question? [With arrays, why is it the case that a\[5\] == 5\[a\]?](https://stackoverflow.com/questions/381542/with-arrays-why-is-it-the-case-that-a5-5a) – user3840170 Apr 21 '22 at 07:58
  • You completely answered my question. I didn't think about implicit conversion at all. @Jarod42 Also, I don't think this is a repetitive problem, which can provide some directions for some newcomers to consider similar problems. – LandP Apr 21 '22 at 08:03
  • 1
    Please copy and paste all that as formatted text instead of an image. I know it's a pain, but there are [plenty of good reasons for not using screenshots of text](https://meta.stackoverflow.com/a/285557/354577). – ChrisGPT was on strike Apr 29 '22 at 19:17

1 Answers1

2

Indicate in cppreference that the expression representing the subscript must be a prvalue of unscoped enumeration or integral type.

// as we know ,i is a lvalue

So why can a for loop that traverses a built-in array, which beginners have learned, be compiled.

A glvalue expression may be implicitly converted to prvalue with lvalue-to-rvalue conversion.

eerorika
  • 232,697
  • 12
  • 197
  • 326