Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

PROGRAMMING CHALLENGE

Name: Anonymous 2010-07-16 18:57


This one should be difficult enough for you guys,

Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i.


My submission, in Scheme


(define (foo num)
  (lambda (x) (+ x num)))

Name: Anonymous 2010-07-16 19:47

>>10
test.c:

#include <stdio.h>

int (*foo(int n))(int) {
    int f(int i) { return n + i; }
    return f;
}

int main(int argc, char* argv[]) {
    int (*fun)(int) = foo(10);
    printf("%d\n", fun(2));
    return 0;
}


With GCC 4.5 gcc -std=c99 -O2 -S -c test.c, the assembly listing on x86-64 looks like this:


    .file    "test.c"
    .text
    .p2align 4,,15
    .type    f.1848, @function
f.1848:
.LFB4:
    .cfi_startproc
    movl    (%r10), %eax
    addl    %edi, %eax
    ret
    .cfi_endproc
.LFE4:
    .size    f.1848, .-f.1848
    .p2align 4,,15
.globl foo
    .type    foo, @function
foo:
.LFB3:
    .cfi_startproc
    leaq    -36(%rsp), %rax
    ret
    .cfi_endproc
.LFE3:
    .size    foo, .-foo
    .section    .rodata.str1.1,"aMS",@progbits,1
.LC0:
    .string    "%d\n"
    .text
    .p2align 4,,15
.globl main
    .type    main, @function
main:
.LFB5:
    .cfi_startproc
    subq    $8, %rsp
    .cfi_def_cfa_offset 16
    movl    $10, %edi
    call    foo
    movl    $2, %edi
    call    *%rax
    movl    $.LC0, %edi
    movl    %eax, %esi
    xorl    %eax, %eax
    call    printf
    xorl    %eax, %eax
    addq    $8, %rsp
    .cfi_def_cfa_offset 8
    ret
    .cfi_endproc
.LFE5:
    .size    main, .-main
    .ident    "GCC: (GNU) 4.5.0"
    .section    .note.GNU-stack,"x",@progbits

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List