I'm writing a function that stores an integer as separate bytes in an array, see here.

I've got to the part when I detect a button push, and increment the digit over the cursor. If this digit gets to 9, the next push should reset it back to 0. The following code works:

digit[curpos]++ ; // increment digit
   digit[curpos] = (digit[curpos] > 9) ? 0 : digit[curpos] ; // if > 9, reset to 0

However, I figured I could use the remainder, but my code thinks otherwise:

digit[curpos] = ((digit[curpos]++) % 10)  ; // doesn't work

An added complication (and the reason I wanted to tidy this up) is that the MSD (in digit[4], so curpos = 4) only has a range of 0 to 3, giving the number a maximum of 39999. I will need to add code to deal with this case later.

Recommended Answers

All 4 Replies

As odd as it sounds:

p = (p + 1) % 10; // works
p = (p++) % 10; // doesn't work

So if you want to get it all on a single line, do the the top line.

Is there a reason you are using strings instead of simple integers? It would be a lot simpler to manipulate an integer then convert it to a string for display purposes.

#include <stdio.h>
#include <string.h>

int main ()
{
    int x = 39989;
    char result[80];
    for(int i = 0; i < 11; i++)
    {
        x = (++x) % 40000;
        sprintf(result,"%d", x);
        printf("%s\n", result);
    }
    return 0;
}

[edit]
>>p = (p++) % 10; // doesn't work

Use pre-increment
x = (++x) % 10; // works
[/edit]

Try

digit[curpos] = (++digit[curpos]) % 10;

The reason your code doesn't work is because it uses a postfix increment operator. This means that the incrementation takes places after the statement it can be found in has been executed. That is, the first piece of code below can be expanded into the second one.

i = 9;
i = (i++) % 9;
i = 9;
i %= 9; /* I prefer to cut corners, but you know what this translates into */
i == 0 /* Now i is equal to i % 9. i was 9 before the above statement, so now i is 0 */
i++; /* We increment i, which is now 0. Therefore, after this statement, i will be 1 */
i == 1

What you want to do is use the prefix increment operator. As you'd expect, it first increments the variable and then uses the new result. To give a matching exemple,

i = 9;
i = (++i) % 9;
i = 9;
++i; /* We increment i, which was 9 previously */
i == 10 /* i is now 10 */
i %= 9 /* Divide by 9 */
i == 1 /* 10 % 9 is 1 */

I hope this clarifies things for you, I haven't had much sleep last night.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.