Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert functions that use C++ pass-by-reference into C?

Tags:

c++

c

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?

like image 406
Caslav Avatar asked Dec 12 '22 09:12

Caslav


1 Answers

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.

like image 138
Doug T. Avatar answered Dec 14 '22 23:12

Doug T.