Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C passing variable by reference [closed]

I have the following code:

main()
{
 uint8_t readCount;
 readCount=0;
 countinfunc(&readCount);
}

countinfunc(uint8_t *readCount)
{
 uint8_t i;
 i = readCount;
 ....
}

Problem is that when it enters in the function the variable i has a different value then 0 after the assignment.

like image 887
dare2k Avatar asked Jan 31 '26 08:01

dare2k


2 Answers

It's because in countinfunc the variable is a pointer. You have to use the pointer dereference operator to access it in the function:

i = *readCount;

The only reason to pass a variable as a reference to a function is if it's either some big data that may be expensive to copy, or when you want to set it's value inside the function to it keeps the value when leaving the function.

If you want to set the value, you use the dereferencing operator again:

*readCount = someValue;
like image 186
Some programmer dude Avatar answered Feb 01 '26 23:02

Some programmer dude


countinfunc(uint8_t *readCount)
{
 uint8_t i;
 i = *readCount;
 ....
}
like image 29
MOHAMED Avatar answered Feb 02 '26 01:02

MOHAMED