I have a piece of code that is written in C++ and need 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With