簡體   English   中英

什么typedef沒有類型意味着什么?

[英]What does typedef with no type mean?

從標准N1570 6.7.8

typedef聲明不引入新類型,只引用所指定類型的同義詞。

所以我預計不可能這樣寫:

typedef t;
t *t_ptr;

它應該無法編譯,因為沒有類型來引入提供的同義詞。 但它很好: 演示 這是什么意思,為什么編譯?

這依賴於以下事實:缺少類型規范默認為int

所以,你的陳述

 typedef t;

是相同的

 typedef int t;

如果有適當的警告級別,編譯器會發出警告:

warning: type defaults to ‘int’ in declaration of ‘t’ [-Wimplicit-int]
 typedef t;
         ^

也就是說, 不要依賴這種行為,“隱式int”規則自C99以來已經過時。

它默認為int

編譯器警告顯示正在發生的事情:

#1 with x86-64 gcc 8.2
<source>:1:9: warning: type defaults to 'int' in declaration of 't' [-Wimplicit-int]
 typedef t;

C99開始,刪除了隱式 int規則。 所以這不適用於C99以后。

如果在GCC中使用-pedantic-errors編譯器選項(意味着嚴格符合標准), 則會發出錯誤 看到這里

如果您有興趣, C89標准中的相關部分允許:

3.5.2類型說明符
每個類型說明符列表應為以下集合之一; 類型說明符可以按任何順序出現,可能與其他聲明說明符混合。

  • 空虛
  • 燒焦
  • 簽名的char
  • 無符號字符
  • short,signed short,short int或signed short int
  • unsigned short或unsigned short int
  • int,signed,signed int或no type specifiers

所以在C99中 ,刪除了上面粗體( 或沒有類型說明符 )的最后部分。

typedef聲明定義對象或指針類型的同義詞。 因此,您應指定要為其創建同義詞的類型以及要用作同義詞的名稱。

例如:

// 'byte_t' is a synonym for 'unsigned char'
typedef unsigned char byte_t;
// 'handler_t' is a synonym for 'void (*)(int)', a function pointer
typedef void (*handler_t)(int);
// 'short_p' is a synonym for 'short *'
typedef short * short_p;
// 'record' is a synonym for an anonymous structure
typedef struct {
    int a;
    char *b;
    } record;
// 'error_p' is a synonym for a pointer to 'struct error', defined somewhere else
typedef struct error *error_p;

您引用的源代碼中有更多示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM