Search code examples
cpointerspicxc8compound-literals

Array Index Types & Warning (752) in XC8 v2.10 C99


First question, so I hope its understandable!

I am initialising a pointer to a compound literal, which is an array of struct pointers. I can then use this pointer as I would normally an array of pointers.

typedef struct
{
    uint32_t test1;
    uint32_t test2;
    uint32_t test3;
    uint32_t test4;
    uint32_t test5;
    uint32_t test6;
    uint32_t test7;
    uint32_t test8;
    uint32_t test9;
    uint32_t test10;
    uint32_t test11;
} TestStruct;

TestStruct* TestStructArray = (TestStruct[])
{
    {
        .test1 = 69,
    },
    {
        .test1 = 69,
    },
    {
        .test1 = 0,
    },
};

When I try to loop through this array later, I use a variable of type size_t for the loop counter, and access the members of the array using the [] array notation.

void main(void)
{
    size_t ArrIdx = 0U;
    while(TestStructArray[ArrIdx].test1 != 0U) \\\\\ <-- warning: (752) conversion to shorter data type
    {
        LocalTestFunction();
        ArrIdx++;
    }
}

When the array size falls below some sort of size threshold, the compiler give the following warning: (752) conversion to shorter data type. Adding more members to the struct, or more members to the array of struct removes the warning. ie.. In this example, initialising another member of the array removes the compiler error.

This warning seems to be pointing to the line where I access the array members with the index of type size_t. It seems that the type used by the compiler for array index's is not constant, and actually depends on the size of the array. This makes it very difficult to prevent truncation or unused memory.

I have compiled this test code in a completely new project and the behaviour remains.

Am I going crazy or have I found some interesting quirk with the optimization?

My build environment is as follows:

  • MPLAB X v5.35
  • XC8 v2.10
  • C99 Standard and Link in C library
  • Warning Level : -9
  • Device: PIC18F46K20
  • Optimisation: Space (PRO)

Example Project


Solution

  • This warning seems to be pointing to the line where I access the array members with the index of type size_t. It seems that the type used by the compiler for array index's is not constant, and actually depends on the size of the array.

    C does not have any sense of an inherent index type of an array. It is allowed to access an array via an index expression of any integer type, and that does not imply any conversion of the index to a particular integer type.

    Am I going crazy or have I found some interesting quirk with the optimization?

    I think you have discovered a quirk of the compiler, but it's not clear whether that's related to optimization. Nor is it clear whether the warning signals any bona fide risk. From a C language perspective, however, I see nothing wrong with the code fragments you've posted, neither individually nor together, in C99 or later.