Конкатенация имен переменной в C?

Попробуйте это:

function pause(){
   read -p "$*"
}
8
задан Sinan Ünür 22 February 2010 в 23:04
поделиться

5 ответов

When you find yourself adding an integer suffix to variable names, think I should have used an array.

struct mystruct {
    int class[6];
};

int main(void) {
    struct mystruct s;
    int i;
    for (i = 0; i < 6; ++i) {
        s.class[i] = 1000 + i;
    }

    return 0;
}

Note: A C++ compiler will barf at this because of class. You will need to figure out a different name for that field if you plan to compile this code as C++.

45
ответ дан 5 December 2019 в 04:33
поделиться

There are dynamic languages where you can do this sort of thing - C is not one of these languages. I agree with Sinan - arrays or STL vectors are the way to go.

As a thought experiment - what would happen if you have 100,000 of these variables? Would you have 100,000 lines of code to initialise them?

6
ответ дан 5 December 2019 в 04:33
поделиться

What you could also do, is write an implementation of a hash map. Since the set of keys (that would be like variable names) of the hash map does not change over time, for each hash map you could keep an array of its keys for iterating efficiently. But that would be a total (crazy) overkill, especially in C ;)

Pretty much anything is possible in C, it's a great language to learn :)

0
ответ дан 5 December 2019 в 04:33
поделиться

The C preprocessor can concatenate symbols, but have you considered just using an array?

1
ответ дан 5 December 2019 в 04:33
поделиться

возможно, вам поможет безопасное CERT-C правило кодирования PRE05-C 'Понять замену макросов при конкатенации маркеров или выполнении строковой оптимизации'. Для получения более подробной информации обратитесь к этой ссылке: https://www.securecoding.cert.org/confluence/display/seccode/PRE05-C.+Understand+macro+replacement+когда конкатенация токенов или выполнение строковой оптимизации.

Для краткости определите сначала макрос JOIN_AGAIN(x,y) (x##y). а потом JOIN(x,y) JOIN_AGAIN(x,y) Макрос JOIN_AGAIN позволяет расширить значение купола петли, которое будет связано с именем var.

Ура! Пьер Буй

0
ответ дан 5 December 2019 в 04:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: