2

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

  • This is not a good question! Please re-format it and ask specifics. Do not post links to pictures. Show us that you actually attempted the problem, then come back and ask! – Retro Gamer May 12 '16 at 21:07
  • Everything @Developer said. You can find a guide on how to ask questions [here](http://stackoverflow.com/help/how-to-ask). – Steve Heim May 13 '16 at 00:38
  • 3
    There's no pass by name in C, so you cannot do that. – n. m. could be an AI May 13 '16 at 10:42
  • I know that C does not working with pass by name mehanism, but pass-by-name could be written in C. I did some research and there are two ways to do that 1) with macro's 2) by using thunk's But I couldn't understand working logic of thunk's in C – Kadir Erceylan May 13 '16 at 11:20
  • 1
    "pass-by-name could be written in C" Macros use pass-by-name indeed. They are not functions but they are the closest thing you can get. There are no thunks in C. You might be able to write a thunk in assembly and call it from C, but that would be "using pass-by-name mechanism in the assembly language". – n. m. could be an AI May 13 '16 at 14:06
  • Could you give me a small function as an example about pass-by-name mechanism in assembly. – Kadir Erceylan May 16 '16 at 12:00

2 Answers2

2

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);
Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
1

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);
}