Modern C and initializing an array

I was today years old when I learned something that modern C can do. Thank you, Bing Copilot, for offering this up and learnin’ me somethin’ new.

At my day job I am porting various WIZnet (and hardware TCP/IP ethernet chip) services over to a new circuit board. We are using the W5500 chip, and making use of the provided I/O library from WIZnet:

Wiznet/ioLibrary_Driver: ioLibrary_Driver can be used for the application design of WIZnet TCP/IP chips as W5500, W5300, W5200, W5100, W5100S, W6100, W6300.

For this project, I have gotten basic Ethernet TCP running, then moved on to port their HTTP server code, followed by their SNMP server. While I may have encountered SNMP during my 1990s employment at Microware when I taught an OS-9 networking course, I have not touched it since then so this was “all new” again to me.

Part of configuring SNMP was an array of structures like this:

dataEntryType snmpData[] =
{
    // System MIB
    // SysDescr Entry
    {
        8, {0x2b, 6, 1, 2, 1, 1, 1, 0},
        SNMPDTYPE_OCTET_STRING, 30, {"Description String"},
        NULL, NULL
        },
    // SysObjectID Entry
    {
        8, {0x2b, 6, 1, 2, 1, 1, 2, 0},
        SNMPDTYPE_OBJ_ID, 8, {"\x2b\x06\x01\x02\x01\x01\x02\x00"},
        NULL, NULL
        },

…and so on. You can find this file here:

ioLibrary_Driver/Internet/SNMP/snmp_custom.c at master · Wiznet/ioLibrary_Driver

When I got to the part where I was adding the ability to send an “SNMP trap” (kind of a push notification to a specific IP address), I saw that it would duplicate the values in this array:

void sendTrap_sysObjectID(void) {
    // Create a dataEntryType for sysObjectID
    dataEntryType sysObjectEntry = {
        8, {0x2b, 6, 1, 2, 1, 1, 2, 0},
        SNMPDTYPE_OBJ_ID, 8, {"\x2b\x06\x01\x02\x01\x01\x02\x00"},
        NULL, NULL
    };
    // Send the trap
    snmp_sendTrap( ...params...);
}

Above, the “sysObjectEntry” array is a duplicate of the entry in my definition table.

This would mean keeping two parts of the code in sync, which is a terrible idea since it creates extra places for error, and also doubles the work. The A.I. suggested using the entry in the array, like this:

snmp_sendTrap(
  managerIP,
  agentIP,
  (int8_t*)"public",
  snmpData[1], // SysObjectID or your custom OID
  6,           // enterpriseSpecific
  1,           // specific trap ID
  1,           // one variable binding
  snmpData[10].oid, SNMPDTYPE_INTEGER, (uint8_t[]){1}, 1 // HighTempState = 1
);

Using “snmpData[1]” is more better, since now I can just change the definition table instead of multiple places hard-coding that information.

BUT, how do I know which entry is [1] versus [7]? I’d have to ensure the table entries stayed in order, then I could use a #define as an index, like this example:

typedef struct
{
	int x,y,w,h;
} BoxStruct;
// Declare an array of boxes, the old fashioned way.
BoxStruct box[] = // Initialize four boxes
{
	{ 0, 0, 100, 10},
	{ 10, 10, 90, 10 },
	{ 20, 20, 80, 10 },
	{ 30, 30, 70, 10 }
};
// Declare an array of boxes, the new fangled way.
#define BOX1    0
#define BOX2    1
#define BOX3    2
#define BOX4    3

That would let me get the data for box[BOX1] or box[BOX4]. Easy.

But if this was a long list of entries, like my SNMP was, and later I added something in between, I’d have to update the array as well as make sure this #define table is updated. Again, more place for error and more work.

The first thought was to declare the array as fixed size and initialize it like this:

// Declare an array of boxes, the new fangled way.
#define BOX1    0
#define BOX2    1
#define BOX3    2
#define BOX4    3
#define BOX_MAX 4
BoxStruct box[BOX_MAX];
box[BOX1] = { 1,1,1,1 };
box[BOX2] = { 2,2,2,2 };
box[BOX3] = { 3,3,3,3 };
box[BOX4] = { 4,4,4,4 };

That makes it easy and obvious, BUT you cannot have those initializes with global variables. You can only initialize that way from a function. This is fine if you want to declare your global array, then initialize like…

void initBoxes (void)
{
    box[BOX1] = { 1,1,1,1 };
    box[BOX2] = { 2,2,2,2 };
    box[BOX3] = { 3,3,3,3 };
    box[BOX4] = { 4,4,4,4 };
}

And that is the approach I would probably take on my “C-like” embedded compilers that do not support all of modern C.

However, the A.I. showed me something I had not seen before. Initializing the array like this:

// Initialize by element number, in order.
BoxStruct box[BOX_MAX] =
{
	[BOX1] = { 0, 0, 100, 10},
	[BOX2] = { 10, 10, 90, 10 },
	[BOX3] = { 20, 20, 80, 10 },
	[BOX4] = { 30, 30, 70, 10 }
};

Huh? I did a quick check on the Online GDB compiler, and that was valid. It even lets you initialize out of order:

// Initialize by element number, out of order.
BoxStruct box[BOX_MAX] =
{
	[BOX3] = { 20, 20, 80, 10 },
	[BOX1] = { 0, 0, 100, 10},
	[BOX4] = { 30, 30, 70, 10 },
	[BOX2] = { 10, 10, 90, 10 }
};

By doing it that way, I could “see” the label match the data, regardless of whatever the number the label was set to. And, if I messed up the #defines later (duplicate value or whatever), a “good compiler” with warnings enabled should alert me of that (at least, GCC does).

For my specific use, this is a great solution, and it works in whatever compiler the Microchip MPLAB X IDE is using for PIC24 processors.

Here is my test code:

/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
/*---------------------------------------------------------------------------*/
// Typedef
/*---------------------------------------------------------------------------*/
typedef struct
{
	int x,y,w,h;
} BoxStruct;
/*---------------------------------------------------------------------------*/
// Globals
/*---------------------------------------------------------------------------*/
// Declare an array of boxes, the old fashioned way.
BoxStruct foo[] = // Initialize four boxes
{
	{ 0, 0, 100, 10},
	{ 10, 10, 90, 10 },
	{ 20, 20, 80, 10 },
	{ 30, 30, 70, 10 }
};
// Declare an array of boxes, the new fangled way.
#define BOX1    0
#define BOX2    1
#define BOX3    2
#define BOX4    3
#define BOX_MAX 4
// Initialize by element number, in order.
BoxStruct foo2[BOX_MAX] =
{
	[BOX1] = { 0, 0, 100, 10},
	[BOX2] = { 10, 10, 90, 10 },
	[BOX3] = { 20, 20, 80, 10 },
	[BOX4] = { 30, 30, 70, 10 }
};
// Initialize by element number, out of order.
BoxStruct foo3[BOX_MAX] =
{
	[BOX3] = { 20, 20, 80, 10 },
	[BOX1] = { 0, 0, 100, 10},
	[BOX4] = { 30, 30, 70, 10 },
	[BOX2] = { 10, 10, 90, 10 }
};
/*---------------------------------------------------------------------------*/
// Prototypes
/*---------------------------------------------------------------------------*/
void ShowBox (BoxStruct box);
/*---------------------------------------------------------------------------*/
// Functions
/*---------------------------------------------------------------------------*/
void ShowBox (BoxStruct box)
{
	printf ("x:%d y:%d w:%d h%d\r\n", box.x, box.y, box.w, box.h);
}
int main()
{
	printf ("---foo---\r\n");
	for (int idx=0; idx<4; idx++)
	{
		ShowBox (foo[idx]);
	}
	printf ("---foo2---\r\n");
	for (int idx=0; idx<4; idx++)
	{
		ShowBox (foo2[idx]);
	}
	printf ("---foo3---\r\n");
	for (int idx=0; idx<4; idx++)
	{
		ShowBox (foo3[idx]);
	}
	return 0;
}
/*---------------------------------------------------------------------------*/
// End of main.c

You can mess with it online here:

https://onlinegdb.com/G73hxWSQuN

I wonder what other stuff has been added to C over the years that I do not know about…

Until next time…

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.