phoeNix
phoeNix

Reputation: 63

Pass-by-name implementation in C

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?

Upvotes: 0

Views: 566

Answers (3)

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.

Upvotes: 0

Steve Summit
Steve Summit

Reputation: 48026

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

Upvotes: 0

Johannes Weiss
Johannes Weiss

Reputation: 54081

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

Upvotes: 3

Related Questions