-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
  • 80,142
  • 18
  • 159
  • 256

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,590
  • 1
  • 14
  • 26
4

because

return ( (a++) % 4 );

is similar to

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

Try

return (++a) % 4;
David Heffernan
  • 587,191
  • 41
  • 1,025
  • 1,442
DoctorMoisha
  • 1,483
  • 13
  • 22
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
  • 200,579
  • 13
  • 144
  • 260
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
  • 587,191
  • 41
  • 1,025
  • 1,442
0
   return ( (a++) % 4 );

change to

   return ( (++a) % 4 );

You will get what you want

Jeegar Patel
  • 24,980
  • 49
  • 151
  • 213
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
  • 492
  • 1
  • 5
  • 14
-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
  • 457
  • 1
  • 6
  • 18