cparameter-passingthunkcallbynamepass-by-name

Pass by name implementation in C


How can I calculate the value of the arithmetic expression š‘–^2 + 3i āˆ’ 1 that is dependent on the index i by using pass-by-name mechanism in C language

9
āˆ‘ i^2 + 3i āˆ’ 1
š‘–=0

through a call to a sum procedure with argument(s) passed by name

Pass by name examples written in C could also help me


Solution

  • I have done such a solution as following it works but I am not sure whether it works with pass-by-name or not, Could you comment my solution?

    #include <stdio.h>
    
    int i;
    typedef int* (*intThunk)(void);
    int* vSubiThunk(void){ return &i; }
    
    int sum(intThunk i){
        return (*i())* (*i()) + (*i() * 3) - 1 ;
    }
    
    int main(void){
        int total = 0;
        for(i=0;i<=9;i++)
            total += sum(vSubiThunk);
    
        printf("%d \n",total);
    }