0

I have referenced the following question:

Using pointers to emulate Pass-by-Reference in a Pass-by-Value function (C and C++)

I am attempting a very similar exercise except instead of implementing a 'swap' function, I'm attempting to implement a function that calculates the cube of an integer number. The perplexing thing for me is I get no output at all, not even the "hello world" test output. In fact all I get is the following:

process exited after 1.967 seconds with return value 3221225477

My code is as follows:

#include <stdio.h>
#include <stdlib.h>

int cube1(int *p);
int cube2(int a);

int main(int argc, char *argv[]) 
{
int x;
int *q;

x = 3;
*q = &x;

//output test  
printf("hello world\n");

printf( "x = %d\n", x );    
printf( "q = %p\n", q );

printf("%d cubed using variable passing by reference =  %d\n", x, cube1(x));
printf("%d cubed using  variable passing by value =  %d\n", x, cube2(x));

system("pause");
return 0;
}

//simulated pass by reference
int cube1(int *p)
{
int temp = *p; 
temp = temp*temp*temp;
*p = temp;

return *p;
}

//standard pass by value
int cube2(int a)
{
    return a*a*a;
}
Trixie the Cat
  • 317
  • 3
  • 18
  • 3
    `*q = &x;` UB here. It should be `q = &x;` perhaps you don't even need `int *q` you can directly call like `cube1(&x)` – kiran Biradar Oct 03 '18 at 16:51
  • 1
    `cube1` expects `int *` as argument, you are passing `int`. But I think this line will lead to undefined behavior if you call it with `cube1(&x)`. – Osiris Oct 03 '18 at 16:55
  • @kiranBiradar thank you for the suggestion, that appears to do the trick. – Trixie the Cat Oct 03 '18 at 17:10
  • @Osiris interesting point, you may be right, however I think due to the simplicity of this program, it appears I can get away with calling cube1(&x) and still get the correct output. However, your suggestion is still valuable to me as a student. Thanks – Trixie the Cat Oct 03 '18 at 17:12

1 Answers1

1

If you emulate pass by reference with pointers you have to pass the pointer to the function, not the variable. *q = &x; should be q = &x; and the function call should be cube1(&x) or cube1(q).

But even if you do that you would invoke undefined behavior since you are calling cube1(&x), which modify x, and pass x as parameter without a sequence point in between. There is no guaranteed order of evaluation.

For example on my system it outputs me:

27 cubed using variable passing by reference =  27
27 cubed using  variable passing by value =  19683

To avoid this you should print x and the return value of the function in two seperate statements:

    printf("%d cubed using variable passing by reference =  ", x);
    printf("%d\n", cube1(&x));
    printf("%d cubed using  variable passing by value =  %d\n", x, cube2(x));
Osiris
  • 2,783
  • 9
  • 17