Note that there are some explanatory texts on larger screens.

plurals
  1. POFunctional Programming (Currying) in C / Issue with Types
    primarykey
    data
    text
    <p>As a dyed-in-the-wool functional programmer I find it hard not to try to shoehorn my favourite paradigm into whatever language I'm using. While writing some C I found I'd like to curry one of my functions, and then pass around the partially applied function. After reading <a href="https://stackoverflow.com/questions/1023261/is-there-a-way-to-do-currying-in-c">Is there a way to do currying in C?</a> and heeding the warnings at <a href="http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html#Nested-Functions" rel="nofollow noreferrer">http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html#Nested-Functions</a> I came up with: </p> <pre><code>#include &lt;stdio.h&gt; typedef int (*function) (int); function g (int a) { int f (int b) { return a+b; } return f; } int f1(function f){ return f(1);} int main () { printf ("(g(2))(1)=%d\n",f1(g(2))); } </code></pre> <p>Which runs as expected. However, my original program works with <code>double</code>s and so I thought I'd just change the appropriate types and I'd be fine:</p> <pre><code>#include &lt;stdio.h&gt; typedef double (*function) (double); function g (double a) { double f (double b) { return a+b; } return f; } double f1(function f){ return f(1);} int main () { printf ("(g(2))(1)=%e\n",f1(g(2))); } </code></pre> <p>This produces things like: </p> <pre><code>bash-3.2$ ./a.out Segmentation fault: 11 bash-3.2$ ./a.out Illegal instruction: 4 </code></pre> <p>with the choice of error being seemingly random. Furthermore if either example is compiled with <code>-O3</code> the compiler itself throws a <code>Segmentation fault: 11</code> itself. I get no warnings from gcc at any point, and I'm not able to figure out what's happening. Does anyone know why the second program fails while the first doesn't? Or better still how to fix the second one?</p> <p>My gcc is <code>i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)</code> and my kernel is <code>Darwin Kernel Version 12.1.0: Tue Aug 14 13:29:55 PDT 2012; root:xnu-2050.9.2~1/RELEASE_X86_64</code>. </p> <p><strong>edit:</strong> To be clear, I understand that what I'm trying to do is stupid. This code isn't going to run on the Curiosity rover, or the NYSE. I'm trying to understand more about how function pointers in (GNU) C work, and explain something interesting I found. I promise never to do anything like this in the real world.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload