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?
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?
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.
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.
"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" ;
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.