當我在一行中初始化一個指向 struct 變數的指標時,我得到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);
}
...
uj5u.com熱心網友回復:
這是個問題:
case NODE_definition:
struct Node *child = node_get_kid(t, 0);
因為您將標簽應用于宣告。標簽只能應用于陳述句。
一種無需重組即可完成此操作的簡單方法是在case標簽之后添加一個空陳述句:
case NODE_definition:
;
struct Node *child = node_get_kid(t, 0);
或者使用復合陳述句:
case NODE_definition:
{
struct Node *child = node_get_kid(t, 0);
...
}
一般通過將任何宣告說不過你的代碼將是清潔之前的switch,所以你不必定義這些型別的問題它是什么內部和擔心。
uj5u.com熱心網友回復:
假設這...
當我在一行中初始化一個指向 struct 變數的指標時,我得到
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);
如果您依賴先前的 variable 宣告child,那么剩下的...
child = node_get_kid(t, 0);
... 是一個陳述,因此可以被標記。盡管它實際上是一個由運算式組成的運算式陳述句,但也允許存在所有其他型別的陳述句——break;例如,一個陳述句。需要運算式是不正確的。
至于稍后使用變數,變數宣告的范圍是包含它的最里面的塊(如果有),在這種情況下是switch主體。如果要在 the 之外使用變數,switch則必須在 the 之前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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314999.html
上一篇:使用介面的GO型別轉換和賦值
