-1
vector<long> v = {1,2,3};
long i = v.size();
const long* w = (i != 0) ? &v.front() : NULL;

Can someone explain what is happening on line 3? To me, it feels like v = w. Am I understanding it right?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
OSUCowboy
  • 57
  • 2
  • 6

4 Answers4

4

e1 ? v1 : v2

That's ?: expression where when expression (e1) has true, it returns v1, else returns v2.

Here it means point constant pointer (cannot change address once assigned address) to NULL if v has no value inside. Or the first element's address if v has at least one element inside.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Noah Han
  • 141
  • 1
  • 6
  • 3
    It's a pointer to a long that is const, meaning you cannot change the pointed-to value, but can indeed change where the pointer points. The ternary operator is not just the ?, but is `?:`. – sweenish Feb 24 '21 at 16:00
  • Thank you very much! – OSUCowboy Feb 24 '21 at 16:06
2

it feels like v = w.

No, not at all. v is a std::vector<long> (assuming vector is std::vector) and w is a const long*. Thats two completely unrelated types. You cannot assign one to the other.

Actually your code is similar to:

vector<long> v = {1,2,3};
const long* w = &v[0];

w is a pointer to the first element in the vector. v.front is just a different way to get a reference to the first element. And because in general we cannot know if v has an element at index 0, the author added a check:

vector<long> v = {1,2,3};
long i = v.size();
const long* w;
if ( v.size() != 0) w = &v.front();
else                w = nullptr;

And a less verbose way of writing the same is using the conditional operator:

const long* w = ( v.size() != 0 ) ? &v.front() : nullptr;

Depending on the condition, only one side of : is evaluated, hence out-of-bounds access to element 0 in an empty vector can be avoided.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

"const long* w = (i != 0) ? &v.front() : NULL; " It checks whether vector has elements. If vector has elements, it assigns first elements address to long type pointer. ? is ternary operator. example int a=1;int b=2; (a<b)? "if true do something" : "if false do something" ;

1

const long* w = (i != 0) ? &v.front() : NULL;

w is a pointer to a long constant - not to be confused with a const pointer to a long. The value of the pointer is being initialized to the result of the ternary expression: (i != 0) ? &v.front() : NULL;


The ?: operator returns one of two values depending on the result of an expression.

Source: http://www.cplusplus.com/articles/1AUq5Di1/


If (i != 0) is true then the result will be the address of the reference returned by v.front() (i.e.: the first element in the vector v). If the expression evaluates false then w will be a null pointer.

A good rule to follow to ensure you understand any declaration properly is The "Clockwise/Spiral Rule" - understanding this rule can save you some headaches.

Tom O.
  • 5,730
  • 2
  • 21
  • 35