Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a nice function that passes variables by reference?

Tags:

as in said in the title, I would like to write a "nice" function in cmake that is able to modify a variable which is passed as a parameter into that function.

The only way I can think of doing it is ugly:

Function definition

function(twice varValue varName) set(${varName} ${varValue}${varValue} PARENT_SCOPE) endfunction(twice) 

Usage

set(arg foo) twice(${arg} arg) message("arg = "${arg}) 

Result

arg = foofoo 

It seems to me, there is no real concept of variables that one can pass around at all?! I feel like there is something fundamental about cmake that I didn't take in yet.

So, is there a nicer way to do this?

Thanks a lot!

like image 698
nandaloo Avatar asked Jan 17 '13 09:01

nandaloo


People also ask

How do you pass by reference in a function?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

How can you pass a variable by reference?

?> Pass by reference: When variables are passed by reference, use & (ampersand) symbol need to be added before variable argument. For example: function( &$x ). Scope of both global and function variable becomes global as both variables are defined by same reference.

How do you pass a variable by reference in C++?

Pass by reference is something that C++ developers use to allow a function to modify a variable without having to create a copy of it. To pass a variable by reference, we have to declare function parameters as references and not normal variables.


1 Answers

You don't need to pass the value and the name of the variable. The name is enough, because you can access the value by the name:

function(twice varName)   SET(${varName} ${${varName}}${${varName}} PARENT_SCOPE) endfunction()  SET(arg "foo") twice(arg) MESSAGE(STATUS ${arg}) 

outputs "foofoo"

like image 195
Philipp Avatar answered Nov 03 '22 00:11

Philipp