[ create a new paste ] login | about

Link: http://codepad.org/WC3Ojunt    [ raw code | output | fork | 1 comment ]

joshua_cheek - C, pasted on Nov 26:
#include <stdio.h>

int i;

//pass by name
#define THREE_TIMES( a ) \
({                       \
  int total = 0;         \
  total += a;            \
  ++i;                   \
  total += a;            \
  ++i;                   \
  total += a;            \
  total;                 \
})
  
//same function, pass by value
int three_times( int a )
{
  int total = 0;       
  total += a;          
  ++i;                 
  total += a;          
  ++i;                 
  total += a;          
  return total;               
}


//called both ways
int main( )
{

  int array[] = {1,2,3};
  
  i = 0;
  printf( "pass by name: %d\n"  , THREE_TIMES(array[i]) );
  
  i = 0;
  printf( "pass by value: %d\n" , three_times(array[i]) );

  return 0;
}


Output:
1
2
pass by name: 6
pass by value: 3


Create a new paste based on this one


Comments:
posted by joshua_cheek on Nov 26
Shows that the same function can be implemented as pass by name and pass by value, and shows how the results differ.

You can see what it looks like after the macro gets evaluated at http://codepad.org/QHkIOPAP#comment-0ip5A9kp
reply