在 C 中连接变量名? [英] Concatenating Variable Names in C?

查看:32
本文介绍了在 C 中连接变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 C 中连接变量名?具体来说,我有一个 struct,其中包含 6 个类似的变量,称为 class1class2class3 等.

Is it possible to concatenate variable names in C? Specifically, I have a struct that contains 6 similar variables in it called class1, class2, class3, etc.

我想通过 for 循环来为每个变量分配一个值,但如果不以某种方式将变量名称与 for 循环计数器的值连接起来,我就看不到如何做到这一点.

I want to run through a for loop to assign each variable a value, but I can't see how to do it without somehow concatenating the variable name with the value of the for loop counter.

我还能怎么做?

推荐答案

当你发现自己给变量名添加了整数后缀时,想想我应该使用数组.

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;
}

注意: C++ 编译器会因为 class 而对此感到厌烦.如果您打算将此代码编译为 C++,则需要为该字段找出不同的名称.

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++.

这篇关于在 C 中连接变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆