I have a C function:
static uint8_t func( uint8_t a )
{
return ( (a++) % 4 );
}
When I call it:
uint8_t b = 0;
b = func(b);
I found b
still is 0 not 1. Why?
I have a C function:
static uint8_t func( uint8_t a )
{
return ( (a++) % 4 );
}
When I call it:
uint8_t b = 0;
b = func(b);
I found b
still is 0 not 1. Why?
When you use post increment, the value will be incremented after the expression is evaluated.
That means First it will substitute a
in expression and evaluate it, after the completion of evaluation it will increment a
.
return ( (a++) % 4 );
here it will take as
return ( (0) % 4 ); // after this expression is solved 'a' becomes 1
If you want to return 1
use pre-increment-
return ( (++a) % 4 );
In this case before evaluating the expression it will increment a
.
return ( (1) % 4 ); // so it will return 1.
or
return ((a+1)%4);
you can use above expression also. it wont modify the value of a
what you have received.
because
return ( (a++) % 4 );
is similar to
uint8_t result = a%4;
a = a + 1;
return result;
Try
return (++a) % 4;
The line
return ( (a++) % 4 );
is equivalent to:
unit8_t temp = ( a % 4 );
a++;
return temp;
That's how postfix increment operators work. The evaluate to their value and increment the value of objects after the expression they are used in has been evaluated.
You use the post-increment operator which increments after the expression is evaluated.
So the expression (a++) % 4
yields the same value as a % 4
.
However, there's no point modifying the parameter, passed by value of course. Write it like this:
static uint8_t func(uint8_t a)
{
return (a+1) % 4;
}
return ( (a++) % 4 );
change to
return ( (++a) % 4 );
You will get what you want
I think you should use ++a
because in a++
increment is done after using the value of a
and in ++a
value is used after the increment.
You can modify your code as:
static void func( uint8_t *a )
{
*a=++(*a) % 4;
}
and call it with:
uint8_t b = 0;
func(&b);