2

I saw the code below in this answer to What is your favorite C programming trick?

What does this piece of code do? How is it useful?

double normals[][] = {
    #include "normals.txt"
};
Community
  • 1
  • 1
hari
  • 9,439
  • 27
  • 76
  • 110

4 Answers4

5

This uses the preprocessor to initialize an array.

It's basically inlining the code that populates the array with values, by reading it from an external text file. Note that this requires that "normals.txt" be filled with values that match the C syntax, ie:

{0, 0, 1},
{0, 1, 0},
{1, 0, 0}
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    @hari: Yes - it's just using the file contents of that file and "dumping" it into the source, inline... – Reed Copsey Oct 20 '11 at 21:40
  • You might want to add that preprocessing is the step that's done before compiling, to avoid confusion with loading the file at runtime. :) This "trick" is useful to import (for example generated) data which only changes when developing an application, since when it's compiled, the data is compiled statically into the executable and won't change anymore, even if the input file itself changes. – CodeCaster Oct 20 '11 at 21:40
  • @Blagovest Buyukliev: So in normal case, what ever "#include" has, it just replaces its content at the place its called. correct? – hari Oct 20 '11 at 21:42
  • 1
    @hari: Yes - this is how "include" works in C's preprocessor normally. C doesn't really care about ".h" or ".c" or any other file types - #include just reads that file, at compile time, and inserts it into the current file. – Reed Copsey Oct 20 '11 at 21:42
0

The 2D array is initialised with the contents of the file "normals.txt", which presumably contains valid C code, and is probably shared with other code or is the output from other software.

sblair
  • 1,085
  • 2
  • 13
  • 22
0

Using the preprocessor directive #include will paste in-place any code from the file it references ... thus whatever is inside of "normals.txt" would be text formatted as valid C-syntax code that fit in the array initializer list for normals.

Since preprocessing takes place before the actual compilation step, this will create valid C-code to initialize the normals 2D array without the coder having to create a lot of text in the actual .c file that initializes the values of the array.

Jason
  • 31,834
  • 7
  • 59
  • 78
0

This makes for ugly code. A much cleaner option would be to have whatever is generating the normals.txt file to just generate a .c file that has the full array declaration.

TJD
  • 11,800
  • 1
  • 26
  • 34