Get data size of array initialized from file
06:15 17 Feb 2026

I am writing a program. The input file in.txt looks like this:

{ 1, 2, 3 }

In the program, I want to simplify my life and write:

#define MAX_ELEMENTS (20)

int a [ MAX_ELEMENTS ] =
#include "in.txt"
;

instead of parsing in.txt with fopen(), fread()...

What I want is to be able to know in the program how many data elements I actually have, in this example 3. The input file might have fewer or more elements (and changing the input file will require a rebuild, of course). There will be an undefined behavior if the number of elements is bigger than MAX_ELEMENTS - which is expected. I take the responsibility to define MAX_ELEMENTS large enough.

So the related questions are:

  1. How can I get the number of elements read from the file?
  2. How can I tell the compiler to initialize the rest of the values in a[] to 0, if they are not initialized from the file?

My ideas:

  1. Loop through the values left-to-right and count non-zero values. A significant problem occurs if one of the values "in the middle" is zero.
  2. Loop right-to-left from the end, skipping zero values, until I find a non-zero value. Bad luck if the last value(s) are zeros.

The worst is if the implicitly initialized values (i.e., not from the file) are non-zeros.

c initialization