Divanshu
Divanshu

Reputation: 426

Why this C++ code works the way it works?

# include <iostream>
using namespace std;

int main(void)
{
     char *name = "Stack overflow";

     cout << *&name << endl;
     cout << &*name << endl;    // I don't understand why this works

     return 0;
 }

I understand how the first "cout" statement works but unable to understand why and how the second one works.

Upvotes: 1

Views: 117

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

To understand how the second statement works substitute it

cout << &*name << endl;

for

cout << &name[0] << endl;

because *name and name[0] are equivalent and return reference to (lvalue) the first character of the string literal pointed by name.

The last statement is equivalent to

cout << name << endl;

Upvotes: 2

uk4321
uk4321

Reputation: 1078

& and * are opposite operations. The first one takes the address of the array (adding one level of indirection) and then dereferences it (removing one level of indirection). The second dereferences the pointer (removing one level of indirection) and then takes the address of the result (adding one). Either way, you get back to the same value.

Just like 4 / 2 * 2 is the same as 4 * 2 / 2, or just like taking a step back and then forward leaves you at the same place as taking a step forward and then backward.

Upvotes: 7

Related Questions