-1

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?

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268

7 Answers7

5

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.

Sathish
  • 3,740
  • 1
  • 17
  • 28
4

because

return ( (a++) % 4 );

is similar to

uint8_t result = a%4;
a = a + 1;
return result;

Try

return (++a) % 4;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
DoctorMoisha
  • 1,613
  • 14
  • 25
2

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

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;
}
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0
   return ( (a++) % 4 );

change to

   return ( (++a) % 4 );

You will get what you want

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
0

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.

singhiskng
  • 511
  • 1
  • 5
  • 15
-1

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);
Avinash
  • 497
  • 1
  • 6
  • 19