Reputation: 9183
I have the following function in c++:
bool compareThem(int top_limit, int* maximum)
{
if( top_limit >= maximum )
{
cout << "Error, maximum number shown be greater than top_limit.";
}
}
I want a simple comparison between the integer
and integer pointer
, though, logically C++ cannot do it, since with ==
operator, int
and int*
are not of the same type. How should I then solve it?
Upvotes: 2
Views: 3679
Reputation: 5241
In C/C++ you can use the *
and the &
operators to access the value pointed to by an address (pointer) and acquire the address in memory of a value. In your example you try to compare an integer with a pointer, there are a couple of ways I can think of that you might do this (depending on the desired behaviour):
In order to compare the values of the two objects you need to retrieve the value of the address pointed to by the pointer. To do this you need to use the dereference operator to retrieve the value which you can then treat as an integer, consider the following.
bool myFunction(int a, int* pointer_to_b)
{
int b = *pointer_to_b;
return a > b;
// Or the one line: return a > *pointer_to_b;
}
Since addresses are just integers it is possible to compare a integer to the address stored in a pointer however you should avoid doing this sort of thing unless you really need to. Consider:
bool myBadFunction(int a, int* b)
{
return (int*) a > b;
}
I've rarely encountered comparison of an integer to the address of an integer but I have on occasion encountered code comparing the address of a vale to a specific address (but there are usually alternatives and I don't recommend it). For how you might achieve this see the following.
bool myAlmostUselessFunction(int a, int* b)
{
int *address_of_a = &a; //< take the address of a
return address_of_a > b;
}
Upvotes: 1
Reputation: 50006
What this code does
bool compareThem(int top_limit, int* maximum)
{
if( top_limit >= maximum )
is comparing top_limit
integer value, with address inside maximum
pointer variable. To get value of variable to which pointer points, you must dereference pointer variable, which is done with * operator: *maximum
.
Upvotes: 3
Reputation: 65630
Just dereference maximum
:
if (top_limit >= *maximum)
// ^
This will compare the int
top_limit
with the int
stored at the memory location pointed to by maximum
.
This is one of the fundamentals of C++ and should be covered in your introductory book.
Upvotes: 7