Pass-by-name implementation in C

528 views Asked by At

I know that C uses pass-by-value and we can emulate pass-by-reference with the help of pointers. But, for example, in order to calculate a simple mathematical expression, how do I implement pass-by-name (which is kind of lazy evaluation but not exactly) in C?

3

There are 3 answers

0
Alexandre Washington On

An example of "pass-by-name" in C preprocessor is: #define PROD(X,Y) ((X)*(Y)). The substitution is textual, so the extra parenthesis pairs inside is needed. In fact, #define PROD(X,Y) (X*Y) when called this way: PROD(A+B) instead of ((A+B)*(A+B)) would produce (A+B*A+B), which is not mathematically equivalent.

8
Johannes Weiss On

C is only pass-by-value. You can't pass by reference or name. With the pre-processor you can do various hacks but not in the C language.

Sometimes, people call passing a pointer "pass-by-reference" but this is not the case. The pointer is passed by value like anything else. C++ is a different story but you asked about C.

You might also be interested in this article discussion this at length

1
Steve Summit On

The parameter substitution used by function-like preprocessor macros is sometimes described as being "pass by name".