Thread: Array index syntax question

  1. #1
    Registered User ChipS's Avatar
    Join Date
    Oct 2011
    Posts
    16

    Array index syntax question

    I found this way of resolving array indexes in a code base. Does anyone know how this is able to resolve this define to the appropriate array index?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    #define PARAMS1 1,1,0
    #define PARAMS2 1,1,2
    
    
    int main()
    {
        u_int16_t temp[4] = {0};
        
        temp[1,1,0 / 2] = 5;
        temp[1,1,2 / 2] = 6;
    
    
        printf("temp1 index %d\n", (1,1,0)/2); // resolves to index 0
        printf("temp2 index %d\n", (1,1,2)/2); // resolves to index 1
        
        for(int i = 0; i < sizeof(temp)/(sizeof(u_int16_t)); i++)
        {
            printf("temp[%d] = %d\n", i, temp[i]);
        }
    
    
        return 0;
    }
    
    Output:
    
    temp1 index 0
    temp2 index 1
    temp[0] = 5
    temp[1] = 6
    temp[2] = 0
    temp[3] = 0
    Edit:

    It looks like this syntax returns the last value in the list. If anyone can add additional background on what the compiler does with this syntax it would be much appreciated!
    Last edited by ChipS; 11-30-2022 at 11:58 AM.

  2. #2
    Registered User
    Join Date
    Sep 2022
    Posts
    55
    Quote Originally Posted by ChipS View Post
    It looks like this syntax returns the last value in the list.
    Correct. This is how the comma operator works.
    Comma operator - Wikipedia
    [...] the comma operator [...] is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type) [...]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Syntax Question for Array in C
    By nafix in forum C Programming
    Replies: 10
    Last Post: 05-25-2012, 08:19 PM
  2. Replies: 8
    Last Post: 04-04-2012, 09:03 PM
  3. Array Syntax Versus Pointer Syntax
    By LyTning94 in forum C++ Programming
    Replies: 6
    Last Post: 12-06-2011, 10:56 AM
  4. Array Index: A simple question?
    By logicwonder in forum C Programming
    Replies: 18
    Last Post: 01-06-2006, 03:26 AM
  5. linked list inside array of structs- Syntax question
    By rasmith1955 in forum C Programming
    Replies: 14
    Last Post: 02-28-2005, 05:16 PM

Tags for this Thread