[英]Expected expression and undeclared identifier error
当我在一行中初始化一个指向结构变量的指针时,我得到error: expected expression
,但是如果我在没有声明的情况下定义变量,它就可以工作。 我想在一行中定义所有结构指针,而不先进行前向声明,因为否则我的文件会变得很长。
关于如何解决这些问题的任何建议? 或者没有办法规避这个问题?
...
//a Node class is defined before, similar to a Node in a linked list
struct Node *buildast(struct Node *t) {
int tag = node_get_tag(t);
switch (tag) {
//i dont want to keep declaring my variables likes below
struct Node *root;
struct Node *everything_else;
case NODE_translation_unit:
//To fix my issue, I declared my variables before
root = node_alloc_str_copy(AST_ROOT, node_get_str(t));
everything_else = node_get_kid(t, 0);
node_add_kid(root, everything_else);
return buildast(everything_else);
case NODE_definition:
//i want to define my struct pointert to a Node in
//one line like below but get an error
//when I try to use the below variable later, I get an
//undeclared identifier to 'child'
struct Node *child = node_get_kid(t, 0); //this line gives an error
if (node_get_num_kids(child) <= 1) {
node_add_kid(t, child);
return buildast(child);
}
...
这是个问题:
case NODE_definition:
struct Node *child = node_get_kid(t, 0);
因为您正在将 label 应用于declaration 。 一个 label 只能应用于一个语句。
无需重组即可执行此操作的一种简单方法是在case
label 之后添加一条 null 语句:
case NODE_definition:
;
struct Node *child = node_get_kid(t, 0);
或者使用复合语句:
case NODE_definition:
{
struct Node *child = node_get_kid(t, 0);
...
}
但是,一般来说,通过在switch
之前放置任何声明,您的代码会更清晰,因此您无需在其中定义任何内容,也不必担心这些类型的问题。
假设这...
当我在一行中初始化一个指向结构变量的指针时,我得到
error: expected expression
,但是如果我在没有声明的情况下定义变量,它就可以工作。
...旨在描述为此标记的错误...
case NODE_definition:
//i want to define my struct pointert to a Node in
//one line like below but get an error
//when I try to use the below variable later, I get an
//undeclared identifier to 'child'
struct Node *child = node_get_kid(t, 0); //this line gives an error
...你误解了问题的本质。 如果确实为此发出的错误消息是“预期表达式”,那么您应该切换到更好的编译器,因为该诊断极具误导性。
与 GCC 对同一行的诊断进行对比:
t.c:11:13: error: a label can only be part of a statement and a declaration is not a statement struct node *child = node_get_kid(t, 0);
如果您依赖于先前的变量child
声明,那么剩下的......
child = node_get_kid(t, 0);
...是一个声明,因此可以被标记。 虽然它实际上是一个表达式语句,由一个表达式组成,但所有其他类型的语句也可以在那里——一个break;
声明,例如。 需要表达式是不正确的。
至于稍后使用变量,变量声明的范围是包含它的最里面的块(如果有的话),在本例中是switch
体。 如果你想在switch
之外使用变量,那么你必须在switch
之前声明它(而不仅仅是在case
标签之前):
struct Node *child;
switch (tag) {
// ...
case NODE_definition:
child = node_get_kid(t, 0);
// ...
}
// you can still use 'child' here
如果你只想要它用于一种case
,那么你可以将它插入到一个块中(也称为复合语句):
switch (tag) {
// ...
case NODE_definition: {
struct Node *child = node_get_kid(t, 0);
// ...
// the above declaration of 'child' is in scope (only) up to this point
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.