Accessing variables dynamically in C language

Asked

Viewed 142 times

2

I understand that it is possible to access variables dynamically in Javasscript, but to do this in C, I can’t 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?"

1 answer

4


Language purely does not give. You have two options:

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

     #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]);
     }
    

    Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

    Remembering that in C it is not possible for the variables to have several types of traditional form. As always there are possible tricks to simulate this, but it comes to this question.

  2. If it’s another more complex problem where there really is a need to use an index as any name, let it be a string that can be manipulated, so the solution is to do what Javascript did and gave ready for your user, which is to create a table of hash.

    C is a language that delivers the basics, the rest is with the programmer provide. So either you write one or you get a library ready to do it.

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

    One of the best known libraries is the uthash. Another is available on Glib gnome. The Apache Portable Runtime also has his. As well as the Apple. Another known is the Hthash. One more.

  • @OP as the bigown already said, only using "hashes". This is because it is really what Javascript does. Variable names in C are only abbreviations for places in memory

  • @Lucashenrique as in any language, in one form or another :)

  • really, what changes is the level of "iterations" =P

Browser other questions tagged

You are not signed in. Login or sign up in order to post.