Operation on … may be undefined?

前端 未结 3 1273
抹茶落季
抹茶落季 2021-02-02 06:21

I have the following code

FRAME frameArray[5][10]; // Create the array of frames
int trackBufferFull[5] = {0, 0, 0, 0, 0};// Keeps track of how full the buffer f         


        
相关标签:
3条回答
  • 2021-02-02 06:49

    Line 77 is the line

    trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10;
    

    You are changing trackTail[nodeNumber-1] twice between sequence points: once through ++, and once through assignment.

    This is undefined behaviour.

    The remedy is to rephrase the statement, for example like so:

    trackTail[nodeNumber-1] = (trackTail[nodeNumber-1] + 1) % 10;
    

    or like so:

    trackTail[nodeNumber-1]++;
    trackTail[nodeNumber-1] %= 10;
    
    0 讨论(0)
  • 2021-02-02 07:03

    You're modifying trackTail[nodeNumber - 1] between sequence points. It's like you're assigning

    i = ++i;
    

    which is also undefined behaviour.

    Change your code to something like this:

    trackTail[nodeNumber - 1] = (trackTail[nodeNumber - 1] + 1) % 10;
    
    0 讨论(0)
  • 2021-02-02 07:06
    trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10;
    

    Yep, that's undefined behavior just as the error message says. You're not allowed to modify the same value twice without a sequence point in between. In this case that means you're not allowed to both increment trackTail[nodeNumber-1] using ++ and reassign it using =.

    If you just use + 1 instead of ++, it will work fine.

    0 讨论(0)
提交回复
热议问题