[英]Why does assignment from sizeof alter type of variable being assigned from size_t to int?
該程序編譯時沒有警告,並提供了預期的輸出。
#include <stdio.h>
#include <stddef.h>
int i;
size_t s = sizeof(i);
int main(void){
printf("%zu \n", s);
}
但是該程序無法編譯,並且觀察到以下警告和錯誤:
#include <stdio.h>
#include <stddef.h>
int i;
size_t s;
s = sizeof(i);
int main(void){
printf("%zu \n", s);
}
警告和錯誤:
$ gcc -std=c99 -o sizeof_test sizeof_test.c
sizeof_test.c:6:1: warning: data definition has no type or storage class [enabled by default]
s = sizeof(i);
^
sizeof_test.c:6:1: warning: type defaults to ‘int’ in declaration of ‘s’ [enabled by default]
sizeof_test.c:6:1: error: conflicting types for ‘s’
sizeof_test.c:5:8: note: previous declaration of ‘s’ was here
size_t s;
^
sizeof_test.c: In function ‘main’:
sizeof_test.c:9:5: warning: format ‘%zu’ expects argument of type ‘size_t’, but argument 2 has type ‘int’ [-Wformat=]
printf("%zu \n", s);
^
這是gcc
版本信息:
$ gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
我的理解是,至少在c99或更早的版本中, sizeof
的返回類型為size_t
,例如cppreference中所述 。
如果是這樣,那么如果沒有將sizeof
賦值直接初始化為size_t
變量,那么如何將sizeof
賦值類型轉換為int
類型呢? s
和sizeof
運算符的返回類型都不是int
,那么int
類型從何而來?
問題是您只能在全局范圍內使用變量定義(帶有可選的初始化程序)。 您不能有可執行語句。
當編譯器在全局范圍內看到此消息時:
s = sizeof(i);
由於語句在那里不存在,因此假定它是變量聲明。 從中得到的錯誤和警告如下:
int
,您將同時收到這兩種警告。 int
與上一行中定義的size_t
具有相同的名稱。 printf
格式說明符的警告也隨之出現,因為s
最新定義是int
。 真正的問題是,您不能在所有函數之外分配變量。
size_t s;
s = sizeof(i);
這兩行解釋為:一個具有size_t
類型的全局變量s
和另一個具有隱式類型int
全局變量s
(在C99中無效),並使用sizeof(i)
初始化。
如果您了解這些,則可以了解所有錯誤/警告消息。 它們要么與s
的隱式int
類型有關,要么與定義了兩種不同類型的s
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.