Pass by name implementation in C

788 views Asked by At

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

2

There are 2 answers

1
Kadir Erceylan On BEST ANSWER

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);
}
6
Bernd Elkemann On

There are two completely different topics here:

  • (1) You want to learn C. In C you always pass a value, but that value may be a pointer, which in effect works like pass-by-reference.
  • (2) you want to calculate that summation.

You could use (1) to solve (2) but it is not a good way to do it.

You could use (2) as an example to learn (1).

But it should be very clear that (1) and (2) are not the same thing.

  • This is how you pass a value to a function in C: void f(int i); ... f(123);

  • This is how you pass a pointer to a function in C: void f(int* i); ... int i=123; f(&i);

This is the typical way you would calculate the sum in C:

int sum = 0;
for(int i=0; i<=9; ++i)
    sum += 2 + 3*i - 1;
// now sum contains the sum

If for some reason (e.g. homework requirement?) you want to pass a pointer to calculate the sum then:

void f(int* psum, int i) {
    *psum += 2 + 3*i - 1;
}
...
int sum=0;
for(int i=0; i<=9; ++i)
    f(&sum, i);