I know that a function pointer stores the address of a function.
int fun(int x){
//return something
}
int (pfun*)(int)=&fun;
int main(){
std::cout << &fun << "\n"; // this print out 1
std::cout << fun << "\n" ; // this print out 1
std::cout << &pfun << "\n"; // this print out 0x0022ff40
std::cout << pfun << "\n" ; // this print out 1
}
So my questions are :
1) if the fun() doesn't even have an address how can pfun does point to fun().
2) for example in dynamic binding when I use a pointer function at runtime. does the compiler change pfun value to a real pointer like 0X..... so that at runtime will know which function to call since the names doesn't existe after compilation?
The expressions fun and &fun have the same meaning: &fun which is equivalent to the value stored in pfun, so it is no wonder that the three of them yield the same output. &pfun is the address of the pointer, which is the address of the variable.
Now the question is why 1... well, the answer is that there is no overloaded operator<< that takes an std::ostream and a function pointer, so the compiler tries to find the best match among the existing overloads which happens to be bool (a function pointer is implicitly convertible to bool). The function pointer will be converted to false only if the function pointer is null, which is not the case. The true value is finally printed as 1 (you can check this by doing: std::cout << std::boolalpha << fun which will print true).
If you want to obtain the actual address of the function (in this process) you can force the cast to a void pointer and print the result. This might not be technically correct, but it will give you a number different than 1... Note that the value might differ in different runs and basically has no meaning at all.
operator<< does not have an appropriate overload for printing function pointers. Try this instead.
#include <iostream>
void fun() {}
void (*pFun)() = &fun;
int main ()
{
std::cout << (void*)pFun << "\n";
}
Related
As I know address of array a is the address of first element of this array.
void func(int a[])
{
cout << "address in func: " << &a << endl;;
cout << "GT: " << &a[0] << endl;
}
int main ()
{
int a[] = {0,1,2,3};
cout << "address in main: " << &a << endl;
cout << "address in main a[0]: " << &a[0] << endl;
func(a);
}
Output:
address in main: 0x7ffef67d6790
address in main a[0]: 0x7ffef67d6790
address in func: 0x7ffef67d6778
GT: 0x7ffef67d6790
Why address of array a in func() difference with address of a[0]?
Why address of array a in func() difference with address of a[0]?
Because you're calling the function func() passing a by value. This means the a inside the function func() is actually a copy of the original decayed pointer that you're passing to func() from main(). And since they're different variables, they have different addresses. Thus by writing cout << &a; you're printing the address of this separate local variable named a.
If you want to print the original address, you should write inside func():
void func(int a[])
{
//---------------------------------v---------->removed the &
cout << "address in func: " << a << endl;;
cout << "GT: " << &a[0] << endl;
}
Demo
address in main: 0x7ffcfb0a4320
address in main a[0]: 0x7ffcfb0a4320
address in func: 0x7ffcfb0a4320
GT: 0x7ffcfb0a4320
As it has been explained in the comments, you're not passing the "same" variable to your function.
When you're calling your function, it makes a local copy within it of your array of int.
In order not to waste memory, and let's say you upgrade your program and now, you're not passing to your function an array of int but a std::vector which is quite big, we have in C++ arguments passed by references (myType & myVar).
This is the same than passing an argument by pointers in C.
Passing something by reference actually creates an ALIAS to the variable passed. So you'd now have 2 ways to act on the variable : the variable itself in your main program, and the alias in your function.
Obviously, if you do not want to modify it in the function, you can pass it by const reference (const myType & myVar) which is the same than in C with const *.
It is a fallacy inherited from C that
void func(int a[])
would pass an array to the function.
While int a[] looks like an array you can't actually pass an array to a function. An array always decays to a pointer and the pointer is actually what you pass to the function. So the above is equivalent to writing
void func(int *a)
and maybe now you can see why &a, the address of the local pointer, and &a[0] the address of the first element of the array are different.
It seems that when I pass different integers directly to a function, C++ assigns them the same address as opposed to assigning different addresses to different values. Is this by design, or an optimization that can be turned off? See the code below for an illustration.
#include <iostream>
const int *funct(const int &x) { return &x; }
int main() {
int a = 3, b = 4;
// different addresses
std::cout << funct(a) << std::endl;
std::cout << funct(b) << std::endl;
// same address
std::cout << funct(3) << std::endl;
std::cout << funct(4) << std::endl;
}
The bigger context of this question is that I am trying to construct a list of pointers to integers that I would add one by one (similar to funct(3)). Since I cannot modify the method definition (similar to funct's), I thought of storing the address of each argument, but they all ended up having the same address.
The function const int *funct(const int &x) takes in a reference that is bound to an int variable.
a and b are int variables, so x can be bound to them, and they will have distinct memory addresses.
Since the function accepts a const reference, that means the compiler will also allow x to be bound to a temporary int variable as well (whereas a non-const reference cannot be bound to a temporary).
When you pass in a numeric literal to x, like funct(3), the compiler creates a temporary int variable to hold the literal value. That temporary variable is valid only for the lifetime of the statement that is making the function call, and then the temporary goes out of scope and is destroyed.
As such, when you are making multiple calls to funct() in separate statements, the compiler is free to reuse the same memory for those temporary variables, eg:
// same address
std::cout << funct(3) << std::endl;
std::cout << funct(4) << std::endl;
Is effectively equivalent to this:
// same address
int temp;
{
temp = 3;
std::cout << funct(temp) << std::endl;
}
{
temp = 4;
std::cout << funct(temp) << std::endl;
}
However, if you make multiple calls to funct() in a single statement, the compiler will be forced to make separate temporary variables, eg:
// different addresses
std::cout << funct(3) << std::endl << funct(4) << std::endl;
Is effectively equivalent to this:
// different addresses
{
int temp1 = 3;
int temp2 = 4;
std::cout << funct(temp1) << std::endl << funct(temp2) << std::endl;
}
Demo
The function
const int *funct(const int &x) { return &x; }
will return the address of whatever x is referencing.
So this will, as you expected, print the address of a:
std::cout << funct(a) << std::endl;
The problem with the expression funct(3) is that it is impossible to make a reference of a constant and pass it as a parameter. A constant doesn't have an address, and therefore for practical reasons C++ doesn't support taking a reference of a constant. What C++ actually does support is making a temporary object, initializing it with the value 3, and taking the reference of that object.
Basically, the compiler will, in this case, translate this:
std::cout << funct(3) << std::endl;
into something equivalent to this:
{
int tmp = 3;
std::cout << funct(tmp) << std::endl;
}
Unless you do something to extend the lifetime of a temporary object, it will go out of scope after the function call (or right before the next sequence point, I am not sure).
Since the temporary created by 3 goes out of scope before you create a temporary from 4, the memory used by the first temporary may be reused for the second temporary.
In c++ (GNU GCC g++), my code is "calling" a function without ().
The function is not working, but compiles ok.
More surprisingly, the code always returns 1...
Is there any explanation?
I expected the function name to be just a regular pointer, but seems it's a bit different...
Did I get all 1's only by chance?
#include <iostream>
using namespace std;
void pr ()
{
cout << "sth";
}
int main()
{
pr;
cout << pr; // output: 1
cout << *pr; // output: 1
cout << ≺ // output: 1
}
You're not actually calling pr in your code, you're passing the function pointer to cout. pr is then being converted to a bool when being passed to cout. If you put cout << boolalpha beforehand you will output true instead of 1.
EDIT:
With C++11 you can write the following overload:
template <class RType, class ... ArgTypes>
std::ostream & operator<<(std::ostream & s, RType(*func)(ArgTypes...))
{
return s << "(func_ptr=" << (void*)func << ")(num_args="
<< sizeof...(ArgTypes) << ")";
}
which means the call cout << pr will print (func_ptr=<address of pr>)(num_args=0). The function itself can do whatever you want obviously, this is just to demonstrate that with C++11's variadic templates, you can match function pointers of arbitrary arity. This still won't work for overloaded functions and function templates without specifying which overload you want (usually via a cast).
The name of a function, when used without parentheses, can be implicitly cast to a function pointer. In fact, when you dereference or reference it, it remains nothing but a function pointer, or a poointer to a function pointer, etc. These function pointers, when printed, are implicitly cast to bool, which is why they simply output 1. If you want to output the actual memory address of the function, cast it to a void pointer:
cout<<(void*)pr;
So i have a piece of code with a class like that:
#include<iostream>
#include<cstring>
class stu
{
static int proba;
public:
stu();
static int no(){
return proba;
}
};
int stu::proba=0;
stu::stu()
{
proba=proba+1;
}
int main()
{
std::cout<< stu::no << std::endl;
}
The output is 1.
It does so even if i change stu::no so that it would be only {return 12;}
Why does it happen? How do I fix it??
Change it to std::cout<< stu::no() << std::endl;
Without the (), I believe it's evaluating as a pointer, and not doing what you're expecting.
Edit: As pointed out by #Loomchild, using g++ -Wall will provide further insight as to why it's always 1. The pointer to the static function is always evaluated as true in this context, hence the value being printed.
std::cout<< stu::no << std::endl; prints the address of the function, you're not actually calling it.
std::cout<< stu::no() << std::endl;
calls the function and prints the return value.
In MSVS, this indeed produces a pointer value, with the overload operator << (void*).
Use stu::no() instead of stu::no.
Also, a minor thing really but if you put
using namespace std;
below the #includes you won't have to use std::
Just makes things a little more readable.
stu::no is a function that takes no arguments and returns int.
There is no operator<< that takes functions with your particular signature, so the available overloads are considered. Long story short, the operator<<(ostream&, bool) is the closest match, after function-to-pointer and pointer-to-bool conversions.
Since the function actually exists, its address is definitely non-zero, so the pointer to bool conversion always yields true, which you see as 1.
Make it std::cout<< std::boolalpha << stu::no << std::endl; to see for yourself that it's really a boolean output.
Make it std::cout<< stu::no() << std::endl; to print the result of the function call.
See How to print function pointers with cout? if you want to know what happened in more detail.
still working at C++, but this came up in my book and I don't understand what it's for:
MyClass * FunctionTwo (MyClass *testClass) {
return 0;
}
My question is what is the signifigance of the first indirection operator
(MyClass *[<- this one] FunctionTwo(MyClass *testClass))?
I tried making a function like it in codeblocks, with and without the first * and I didn't see any difference in the way it ran or it's output:
int *testFunc(int *in) {
cout << in << endl;
cout << *in << endl;
return 0;
}
int testFuncTwo(int *in) {
cout << in << endl;
cout << *in << endl;
return 0;
}
I couldn't find anywhere that explained about it in my book.
Thanks,
Karl
The MyClass * means that this function returns a pointer to a MyClass instance.
Since the code is actually returning 0 (or NULL) this means that any caller to this function gets back a NULL pointer to a MyClass object.
I think the following are better examples:
int *testFunc(int *in) {
cout << "This is the pointer to in " << in << endl;
cout << "This is the value of in " << *in << endl;
return in;
}
int testFuncTwo(int *in) {
cout << "This is the pointer to in " << in << endl;
cout << "This is the value of in " << *in << endl;
return *in;
}
void test() {
int a = 1;
cout << "a = " << a;
int output = *testFunc(&a); // pass in the address of a
cout << "testFunc(a) returned " << output;
output = testFuncTwo(&a); // pass in the address of a
cout << "testFuncTwo(a) returned " << output;
}
Apologies, but I've not done C++ in years but the syntax may be a little off.
The general format for a function that takes a single value and returns a single value in C++ is:
return_type function name ( parameter_type parameter_name )
In your case, return_type is MyClass *, which means "pointer to MyClass"
In addition, in your case, parameter_type is also MyClass *.
In other words, your code could be rewritten as:
typedef MyClass *PointerToMyClass;
PointerToMyClass FunctionTwo (PointerToMyClass testClass)
{
return 0;
}
Does that look more familiar?
Given the nature of the question, I'm going to provide a somewhat crude answer.
A pointer points to something:
int x = 123; // x is a memory location (lvalue)
int* y = &x; // y points to x
int** z = &y; // z points to y
In the above code, z points to y which points to x which stores an integral, 123.
x->y->z[123] (this is not code, it's a
text diagram)
We can make y point to another integer if we want or NULL to make it point to nothing, and we can make z point to another pointer to an integer if we want or NULL to make it point to nothing.
So why do we need pointers which point to other things? Here's an example: let's say you have a simple game engine and you want to store a list of players in the game. Perhaps at some point in the game, a player can die by having a kill function called on that player:
void kill(Player* p);
We want to pass a pointer to the player, because we want to kill the original player. Had we done this instead:
void kill(Player p);
We would not kill the original player, but a copy of him. That wouldn't do anything to the original player.
Pointers can be assigned/initialized with a NULL value (either NULL or 0) which means that the pointer will not point to anything (or cease to point to anything if it was pointing to something before).
Later you will learn about references which are similar to pointers except a pointer can change what it points to during its lifetime. A reference cannot, and avoids the need to explicitly dereference the pointer to access the pointee (what it's pointing to).
Note: I kind of skirted around your original question, but the sample code you provided has no inherent meaningful behavior. To try to understand that example without first understanding pointers in a general sense is working backwards IMHO, and you'd be better to learn this general theory first.
If you had something like int * Function() this would return a pointer to an integer. MyClass * just means that the function is going to return a pointer to an object of type MyClass. In c++ user defined objects are treated as first-class-objects, so once you create your own objects they can be passed as a parameter, returned from a subroutine, or assigned into a variable just like the standard types.
In the code blocks you posted there will be no difference in the output to the console because the thing you have changed is the type that the function returns (which is not used), the contents of the functions are identical.
When you define:
int *testFunc(int *in)
You are defining a function which returns a pointer to an int variable.
int testFuncTwo(int *in)
Returns just an int variable.
Zero in this case is undergoing an implicit cast - the first function returns (int*) 0, the second just 0. You can see this implicit cast in action if you change the prototype of your example function from returning a MyClass* to just returning a MyClass - if there's no operator int method in MyClass, you'll get a nice error.