Need help understanding strange array syntax

后端 未结 3 1146
深忆病人
深忆病人 2021-01-29 02:42

I found this bit in a book and I don\'t get what it does:

int index = 1;
...
getArray() [index=2]++;

[index=2]++; looks strange to me,

相关标签:
3条回答
  • 2021-01-29 02:56

    Of course it will be invalid, you're not doing anything with it.

    getArray() [index=2]++;
    

    For demonstration i will switch getArray() with myArray which has { 100, 200, 300, 400 }.
    Than it's equals to:

    myArray[2]++;
    

    myArray[2] will now output: 301
    And index will be: 2

    0 讨论(0)
  • 2021-01-29 03:14

    Let's break that code:

    getArray() [index=2]++;
    

    is equivalent to:

    int[] someArray = getArray();  // Assume that's an int[]
    index = 2;
    someArray[index]++;
    

    The last line is equivalent to:

    someArray[index] = someArray[index] + 1;
    

    If you remove that ++, then the 2nd expression is not a valid statement. It just becomes:

    getArray() [index];
    

    You have to assign that to some L-Value.

    0 讨论(0)
  • 2021-01-29 03:15

    getArray() must return an array of numbers (let's say ints), so getArray() [index=2]++; dissected:

    int index = 2;
    int[] array = getArray();
    array[index] = array[index] + 1;
    
    0 讨论(0)
提交回复
热议问题