简体   繁体   English

从常量字符串初始化静态数组

[英]Initialization of static array from constant string

I'm doing some low-level programming. 我正在做一些底层编程。 For purpose of my task I need to initialize (sometimes hardware-limited) array. 出于我的任务目的,我需要初始化(有时受硬件限制)数组。 It can be just char[], but also unsigned short or whatever. 它可以只是char [],也可以是unsigned short或其他任何形式。

Most readable way is to use just some string of constant, known length. 最易读的方式是只使用一些已知长度的字符串。 To ease the task I've wrote a macro to help myself. 为了简化任务,我编写了一个宏来帮助自己。

#define INI( x ) { (x[0] << 8) | 0x00, (x[1] << 8) | 0x00 }

static const unsigned int tab[] = INI("ab");

int main(){
    return 0;
}

Of course macro above is inside some #ifdef block and depends on architecture it's being build on. 当然,上面的宏在#ifdef块中,并且取决于所构建的体系结构。 The problem I have is that I'm getting error: 我的问题是我遇到了错误:

initializer element is not constant
main.c:3: error: (near initialization for "tab[0]")
initializer element is not constant
main.c:3: error: (near initialization for "tab[1]")

But above code expands to: 但以上代码扩展为:

static const unsigned int tab[] = { ("ab"[0] << 8) | 0x00, ("ab"[1] << 8) | 0x00 };


int main(){
    return 0;
}

Each and EVERY element is not only constant at compile time, but also at preprocessor time. 每个元素不仅在编译时是常量,而且在预处理时也是常量。 It could be even possible to create macro taking every character from the string and doing some manipulation (if only preprocessor would be able to get length of the string and would have some looping option of course). 甚至有可能创建一个宏来获取字符串中的每个字符并进行一些操作(如果只有预处理程序能够获取字符串的长度,并且当然具有某些循环选项)。

So - why compiler isn't able to extract this information and what are my options? 那么-为什么编译器无法提取此信息,我有什么选择? Any help is sincerely appreciated. 真诚的感谢您的帮助。

PS. PS。 I know that it works inside main() as 我知道它在main()中可以作为

const unsigned int tab[] = INI("ab");

but I need it outside any function. 但是我在任何功能之外都需要它。

You cannot do string subscripting / indexing in the preprocessor. 您不能在预处理器中进行字符串下标/索引。 What you could do is change the macro a bit: 您可以做的就是稍微更改宏:

#define ROW( x, y ) { ((x) << 8) | 0x00, ((y) << 8) | 0x00 }

static const unsigned int tab[] = ROW('a' , 'b');

Assuming it's C99, the standard says: 假设它是C99,则标准说明:

The expressions in this compound literal are required to be constant. 该复合文字中的表达式必须是常量。

in reference to an example of a pointer with file scope. 参考具有文件作用域的指针的示例。 It is not sufficient for you to have an expression with constant variables - turns out the expression(s) must be constant as well. 具有常量变量的表达式对于您来说是不够的-事实证明表达式也必须是常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM