Firearrow5235
Firearrow5235

Reputation: 296

On Pointers and Dereferencing

I've been working on learning C++ lately and picked up the book "C++ Through Game Programming". I'm on the chapter on Pointers and I've been presented an example that I have a question about. The code is this:

#include "stdafx.h"
#include <iostream>
using namespace std;

void badSwap(int x, int y);
void goodSwap(int* const pX, int* const pY);

int main()
{
    int myScore = 150;
    int yourScore = 1000;
    cout << "Original values\n";
    cout << "myScore: " << myScore << "\n";
    cout << "yourScore: " << yourScore << "\n\n";
    cout << "Calling badSwap()\n";
    badSwap(myScore, yourScore);
    cout << "myScore: " << myScore << "\n";
    cout << "yourScore: " << yourScore << "\n\n";
    cout << "Calling goodSwap()\n";
    goodSwap(&myScore, &yourScore);
    cout << "myScore: " << myScore << "\n";
    cout << "yourScore: " << yourScore << "\n";
    cin >> myScore;
    return 0;
}

void badSwap(int x, int y)
{
    int temp = x;
    x = y;
    y = temp;
}
void goodSwap(int* const pX, int* const pY)
{
    //store value pointed to by pX in temp
    int temp = *pX;
    //store value pointed to by pY in address pointed to by pX
    *pX = *pY;
    //store value originally pointed to by pX in address pointed to by pY
    *pY = temp;
}

In the goodSwap() function there's the line:

*pX = *pY;

Why would you dereference both sides of the assignment? Isn't that the equivalent of saying "1000 = 150"?

Upvotes: 0

Views: 125

Answers (3)

Andreas Florath
Andreas Florath

Reputation: 4612

Skip the chapter of the book or buy another one: there is no need of using plain pointers in C++ nowadays.

Also there is a std::swap function, that does the things C++isch.

Upvotes: -1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

Why would you dereference both sides of the assignment? Isn't that the equivalent of saying "1000 = 150"?

No, just like the following:

int x = 1000;
int y = 150;

x = y;

is not the equivalent of saying "1000 = 150". You're assigning to the object, not to the value it presently contains.

The below is precisely the same (since the expression *px is an lvalue referring to the object x, and the expression *py is an lvalue referring to the object y; they're literally aliases, not some strange, disconnected version of the objects' numerical values):

int   x = 1000;
int   y = 150;
int* px = &x;
int* py = &y;

*px = *py;

Upvotes: 7

Steephen
Steephen

Reputation: 15824

*px=*py means we are assigning the value not address, from address of py to address of px.

Upvotes: 0

Related Questions