Pre-calculated variable definition with initialization by calculating

Suppose, for example, that I wanted to initialize my variables using a function:

int x[10];
void init_x(){
    for(int i=0; i<10; ++i){
        x[i]=i*i;
    }
}

It does not have to be this exact function, it can be harder and harder for a larger array or other type of int, but in any case the fact is that the result is deterministic. My question is: would it be better (for example, would my program initialize faster each time) to just calculate the result of this in advance and just define it directly?

int x[10]={0, 1, 4, 9, etc...}

Thus, I just run the initialization function once (for example, run the function, then copy + paste the results into the array definition and comment out the code) and more than once and again every time I open the program. (At least that's what I guess)

?

+4
5

, , , , ?

. (, ), . , , .

, () code → .

, . GCC , . X-Macros, , ++.

, Turing-complete ( aes-min, AES128. , , (S-box?) . , , .

+3

, . , . , .

+2

, , . , , .

, :

genx.c(, ):

#include <stdio.h>

int main()
{
    int i;
    printf("int x[] = {");
    for(i=0; i<10; ++i){
        if (i) printf(",");
        printf(" %d", i*i);
    }
    printf(" };\n");
    return 0;
}

:

int x[] = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 };

makefile:

CFLAGS=-Wall -Wextra

app: app.c x.c
        gcc $(CFLAGS) -o app app.c

x.c: genx
        ./genx > x.c

genx: genx.c
        gcc $(CFLAGS) -o genx genx.c

clean:
        rm -f app genx x.c

app.c( ):

#include <stdio.h>

#include "x.c"

int main()
{
    int i;
    for (i=0;i<10;i++) {
        printf("x[%d]=%d\n",i,x[i]);
    }
    return 0;
}

make app, , x.c . x.c genx, genx.

, genx.c , x.c , , .

app:

x[0]=0
x[1]=1
x[2]=4
x[3]=9
x[4]=16
x[5]=25
x[6]=36
x[7]=49
x[8]=64
x[9]=81
+2

. , , , . , , , .

+1

: (, ), ?

. , , .

, , , . .

?

, , , .

0

Source: https://habr.com/ru/post/1654603/


All Articles