I have a piece of code that is written in C++ and nee开发者_JAVA技巧d it in C. I converted most of it but I can't figure out how to convert C++ pass-by-reference in functions to C code, i.e.
Example:
int& a;
it is used in some function as a input variable:
void do_something(float f, char ch, int& a)
When I compile it with C I get compiler errors. Whats the correct way to replace the pass by references in C?
The way to do this in C is to pass by pointer:
void do_something(float f, char ch, int* a)
Also when using a in do_something
instead of
void do_something(float f, char ch, int& a)
{
a = 5;
printf("%d", a);
}
You now need to dereference a
void do_something(float f, char ch, int* a)
{
*a = 5;
printf("%d", *a);
}
And when calling do_something
you need to take the address of what's being passed for a, so instead of
int foo = 0;
d_something(0.0, 'z', foo);
You need to do:
int foo = 0;
d_something(0.0, 'z', &foo);
to get the address of (ie the pointer to) foo.
Because references are not available in C, you'll have to pass a pointer instead:
void do_something(float f, char ch, int *a)
And then in the body of the function you must dereference it in order to get or modify the pointed to value:
*a = 5;
Assuming that x
in an int
, and you want to call the function, you use the &
operator to get its address (convert it to an int *
pointer):
do_something(f, ch, &x)
The closest equivalent is a pointer:
do_something(float f, char ch, int* a)
Having done this, you'll need to change a
-> *a
everywhere within the function, and change calls to the function to pass &a
instead of a
.
There's no equivalent to C++ references in C. However, you could use pointers. They are however variables with their own address, whereas C++ references are just aliases.
function do_something(float f, char ch, int* a)
The "easy", but inadvisable, way is to get help from a helper pointer variable and a #define
feel free to downvote this answer! I would if I could :)
Turn this
int foo(int &a) {
a = 42;
/* ... */
return 0;
}
into
int foo(int *tmpa) { /* & to *; rename argument */
#define a (*tmpa) /* define argument to old variable */
a = 42; /* no change */
/* ... */ /* no change */
return 0; /* no change */
#undef a /* "undo" macro */
}
Note: the introduction of the #define must be done with care
精彩评论