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?

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

You mean this will make c an alias for the passed object, instead of a copy of it, right?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.