I am a newbie in C++ and I’m reading this ebook called Jumping into C++ by Alex Allain which is extremely helpful.
I have recently finished the pointers chapter. There is a practice problem at the end of the chapter where it asks you to write a program that compares the memory addresses of two different variables on the stack and print out the order of the variables by numerical order of their addresses.
So far I got the program running but I am not satisfied if I implemented it the right way and I want an expert opinion about my solution to figure out if I am heading the right direction. Below is my own solution to the problem (comments and tips will be helpful):
// pointersEx05.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
int x,y; // two integer type variables
int *firstVal, *secondVal; // two pointers will point out to an int type variable
std::cout << "enter first value: ";
std::cin >> x; // prompt user for the first value
std::cout << std::endl << "enter second value: ";
std::cin >> y; // prompt user for the second value
std::cout << std::endl;
firstVal = &x; // point to the memory address of x
secondVal = &y; // point to the memory address of y
std::cout << firstVal << " = " << *firstVal; // print out the memory address of the first value and also the value in that address by dereferencing it
std::cout << "\n" << secondVal << " = " << *secondVal; // print out the memory address of the second value and also the value in that address by dereferencing it
std::cout << std::endl;
if(firstVal > secondVal){ // check if the memory address of the first value is greater than the memory address of the second value
std::cout << *secondVal << ", "; // if true print out second value first then the first value
std::cout << *firstVal;
}else if(secondVal > firstVal){ // check if the memory address of the second value is greater than the memory address of the first value
std::cout << *firstVal << ", "; // if true print out first value first then the second value
std::cout << *secondVal << ", ";
}
return 0;
}
This is “correct”, but it’s not well-defined behaviour. You can only compare addresses of elements in the same array, or members of the same instance of a struct. From C99 (6.5.8):*
(empahsis mine)
So this is probably what your supervisor was looking for, and it will probably “work”, but it’s still not valid as far as the language standard is concerned.
* Section [expr.rel] of the C++ standard(s) say something similar, but it’s more verbose, due to caveats for class members and so on. And it also states that anything else is “unspecified” rather than “undefined”.