Accessing variables dynamically in C language

2

I understand that it is possible to access variables dynamically in JavasScript, but doing this in C, I do not find anywhere.

Follow the code in Javascript:

var n1,n2,n3,n4,n5;
n1 = n2 = n3 = n4 = n5 = 0; // define que todas essas variáveis são '0'

for (var i=1; i<=5; i++){
    console.log( window["n"+i] ); // acessa a variável de nome 'n' + número do índice
}

// definimos novos valores para as mesmas variáveis
n1 = "Maçã";
n2 = "Pêra";
n3 = "Uva";
n4 = "Abóbora";
n5 = "Chuchu";

for (var i=1; i<=5; i++){
    console.log( window["n"+i] ); // faz o mesmo que antes, mas agora as variáveis têm seus valores definidos
}

My question is: "How to do the same thing in C language?"

    
asked by anonymous 09.01.2016 / 05:01

1 answer

4

By language purely does not give. You have two options:

  • Do what needs to be done in this case, so instead of creating variables whose index is part of their name, create a variable where the index is highlighted, that is, create a common array . This problem is easily solved like this:

    #include <stdio.h>
    
    int main(void) {
        int n[5] = { 0 };
        for (int i = 0; i < 5; i++) {
            printf("%d\n", n[i]);
        }
        for (int i = 0; i < 5; i++) {
            n[i] = i + 1;
        }
        for (int i = 0; i < 5; i++) {
            printf("%d\n", n[i]);
        }
        return 0;
    }
    

    See running on ideone .

    Remembering that in C it is not possible for variables to have several types in a traditional way. As there are always possible tricks to simulate this, but that's beside the point for this question.

  • If it is another more complex problem where there is really a need to use an index as a name, which is a string that can be manipulated, then the solution is to do what JavaScript did and made ready for your user, which is to create a hash table .

    C is a language that delivers the basics, the rest is with the programmer providing. Then either you write one or arrange a ready library that does this.

    The syntax will never be the best. C is not known to provide many forms of syntactic sugar. Although the preprocessor can help a bit if you know what you are doing and you have creativity. If you do not know, it can cause more problem than solution.

    One of the best-known libraries is uthash . Another is available in Gnome GLib . The Apache Portable Runtime also has yours. Just like Apple . Another known is HtHash . One more .

  • 09.01.2016 / 05:52