www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Comparing function pointers

reply "Freddy" <Hexagonalstar64 gmail.com> writes:
----
import std.stdio;

auto test1(){
	void testFunc(){
	}
	return &testFunc;
}

auto test2(){
	uint a;
	void testFunc(){
		a=1;
	}
	return &testFunc;
}

void main(){
	writeln(test1()==test1());//true
	writeln(test2()==test2());//false
}
----
Is the intended behavior?
Feb 11 2015
next sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
On Wednesday, 11 February 2015 at 18:40:05 UTC, Freddy wrote:
 Is the intended behavior?
Yes. test2 returns a delegate that closes over a separate copy of the local variable, so the data pointer is different each time. You can get the two pointers with .funcptr and .ptr. You'll find .funcptr is the same but .ptr changes.
Feb 11 2015
prev sibling next sibling parent ketmar <ketmar ketmar.no-ip.org> writes:
On Wed, 11 Feb 2015 18:40:03 +0000, Freddy wrote:

 ----
 import std.stdio;
=20
 auto test1(){
 	void testFunc(){
 	}
 	return &testFunc;
 }
=20
 auto test2(){
 	uint a;
 	void testFunc(){
 		a=3D1;
 	}
 	return &testFunc;
 }
=20
 void main(){
 	writeln(test1()=3D=3Dtest1());//true writeln(test2()=3D=3Dtest2());//fal=
se
 }
 ----
 Is the intended behavior?
second thing is not a function, it's a closure (fat pointer internally).=20 each time you calling `test2()`, you creating new closure. so yes, this=20 is intended behavior.=
Feb 11 2015
prev sibling parent Mike Parker <aldacron gmail.com> writes:
On 2/12/2015 3:40 AM, Freddy wrote:
 ----
 import std.stdio;

 auto test1(){
      void testFunc(){
      }
      return &testFunc;
 }

 auto test2(){
      uint a;
      void testFunc(){
          a=1;
      }
      return &testFunc;
 }

 void main(){
      writeln(test1()==test1());//true
      writeln(test2()==test2());//false
 }
 ----
 Is the intended behavior?
Read the section of the documentation about Delegates, Function Pointers, and Closures [1]. Neither of your pointers are actually function pointers. They are both delegates. The second one, as ketmar said, is a closure because it's a delegate with state. To get a function pointer from an inner function, the inner function must be static. Function pointers can't have state. ``` import std.stdio; void printAnInt( int function() fptr ) { writeln( "From function pointer: ", fptr() ); } void printAnInt( int delegate() dg ) { writeln( "From a delegate: ", dg() ); } void main() { static int foo() { return 1; } int bar() { return 2; } printAnInt( &foo ); printAnInt( &bar ); } ``` [1] http://dlang.org/function.html#closures
Feb 12 2015