英文:
Token concatenation using ## for Array value error
问题
I am just using the "Token concatenation with ## " for getting each array.
Some reference i have taken from link
Below is the snippet from my code
macro:
#define Columnsize(x) x##[0]
#define get_arrsize(x) sizeof(x)/sizeof(Columnsize(x))
Code:
uint8 test_array[4][7]= {"ok","me","hello","hi"};
get_arrsize(test_array)
After compilations, I am getting below error
error: pasting ")" and "[" does not give a valid preprocessing token
| #define Columnsize(x) (x)##[0]
Any suggestion how to solve this error? Why this is failed?
英文:
I am just using the "Token concatenation with ## " for getting each array.
Some reference i have taken from https://www.ibm.com/docs/ja/rdfi/9.6.0?topic=definitions-multiple-function-declarations-only
Below is the snippet from my code
macro:
#define Columnsize(x) x##[0]
#define get_arrsize(x) sizeof(x)/sizeof(Columnsize(x))
Code:
uint8 test_array[4][7]= {"ok","me","hello","hi"};
get_arrsize(test_array)
After compilations, I am getting below error
error: pasting ")" and "[" does not give a valid preprocessing token
   | #define Columnsize(x) (x)##[0]
Any suggestion how to solve this error? Why this is failed?
答案1
得分: 1
移除 ##
因为 x[
不是一个有效的(单个)标记。
英文:
> Any suggestion how to solve this error
Remove ##
> Why this is failed?
Because x[
is not a (single) valid token.
答案2
得分: 1
问题出在标记化的方式上。gcc文档有一篇关于标记化和连接的页面,我从中了解到以下内容:
预处理器将源代码分割成大致等同于C编译器标记的标记(例如,文字、标识符或运算符)。这些标记可以与##
运算符结合使用。连接的结果必须再次是一个标记(例如,类似标识符的东西,数字,运算符),而在这里却不是这样,这就是编译器抱怨的原因。
关键在于字符序列[0]
被分隔成三个标记的序列 [
,0
,]
。连接运算符仅使用[
作为其右操作数;结果x[
不是标记。
作为反例,以下示例有效:
#define MAKE_ASSIGN_OP(x) x##=
int main() { int x=1; return x MAKE_ASSIGN_OP(+) 1; }
+
和=
以及它们的连接+=
都是有效的标记。
英文:
The issue is with the way tokenization works. The gcc documentation has a page about tokenization and concatenation from which I glean the following:
The preprocessor separates the source code into tokens which are roughly equivalent to the C compiler tokens (e.g. literals, identifiers or operators). These tokens can be combined with the ##
operator. The result of the concatenation must in turn be a token (for example, an identifier-shaped thing, a number, an operator), which is not the case here, which is why the compiler complains.
The key is that the character sequence [0]
is separated into the three-token sequence [
, 0
, ]
. The concatenation operator uses only [
as its right hand side operator; the result x[
is not a token.
As a counter-example, the following works:
#define MAKE_ASSIGN_OP(x) x##=
int main() { int x=1; return x MAKE_ASSIGN_OP(+) 1; }
Both +
and =
as well as their concatenation +=
are valid tokens.
As an example
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论