0

my question is: I saw(in CUDA examples) that it is possible to use one of the input arguments of a function as output variable. Example: add two integers, c=a+b:

void function AddT(int a,int b,int c){
   c=a+b;
}

But this will not work. The function will not alter the value of c in the main program. Who can I fix it and allow the function to change the value of c?

Mihon
  • 125
  • 1
  • 9

1 Answers1

3

Pass the variable c by reference.

void function AddT(int a, int b, int& c)
{
    c = a + b;
}

This will make it so that any changes to c that you make in the function will remain even after the function ends. My wording is pretty poor here; you can look here for more information:

Pass by Reference / Value in C++

What's the difference between passing by reference vs. passing by value?

Community
  • 1
  • 1
zachyee
  • 348
  • 1
  • 8
  • 3
    You mean this will make `c` an alias for the passed object, instead of a copy of it, right? – Deduplicator Dec 09 '14 at 22:49
  • Yes, thank you for the clarification. The argument you pass when calling the function and c will have different variable names, but will both refer to the same object. – zachyee Dec 09 '14 at 22:51