Reputation: 257
for example, how to implement this C++ code in C ?
void someFunction(type *&outParamOnly) ;
returnType someOtherFunction() ;
...
returnType someOtherFunction()
{
type *data = NULL ;
someFunction(data) ;
...
}
...
void someFunction(type *&outParamOnly)
{
bool condition ;
int array_len ;
...
if(condition) // variable's value passed to this function stays as it was
return ;
...
outParamOnly = new type[array_len] ; // value is moddified and it's reflected in 'someOtherFunction'
...
}
...
I'm asking because I don't know how to create such equivalent. Does it's complex ?. In fact I don't know much about C, but much more about C++ syntax, etc. I'm used to write in C++ and once I tryied C to feel diffrence I'm not doing well when trying to implement what I want. I expect positive answer - that it possible to create some equivalent, but will it be running faster then in C++ or slower ? Please answer.
Upvotes: 0
Views: 225
Reputation: 486
C doesn't have references, but the equivalent is just 'type **'.
void someFunction(type **outParamOnly)
{
if( NULL != outParamOnly )
*outParamOnly = new type[array_len] ;
}
returnType someOtherFunction()
{
type *data = NULL ;
someFunction(&data) ;
}
Note that you need the extra dereference when assigning to what's pointed by outParamOnly and you need to pass a pointer to data when calling someFunction.
Upvotes: 1
Reputation:
C has no reference types, so there's no easy "equivalent" for the syntax you are asking about.
One can use a pointer-to-pointer to emulate that behavior. I'm not sure if that's the appropriate solution, though. Why not just return the value instead of messing around with various levels of pointers if it's an output argument anyway?
Upvotes: 2
Reputation: 46339
The nearest equivalent is a pointer to a pointer; **
. C doesn't have references.
There is a slight difference in the call and the function; you must send a pointer to the variable and dereference it when you want to use it:
void someFunction(type **outParamOnly)
...
*outParamOnly = whatever;
}
someFunction(&data);
This is a fairly typical pattern in C.
Upvotes: 8
Reputation: 19504
You'll need to change the function to accept a pointer-to the thing to be modified. In this case, since the value is a pointer, you'll need to declare the function to accept a double-pointer.
Then, when calling the function, pass the address of the value to be modified.
someFunction(&data) ;
...
void someFunction(type **outParamOnly)
{
*outParamOnly = whatever;
Or, you could return the value from the function instead of returning void
.
Upvotes: 3