我使用的是GCC的以下版本:
$ gcc --version
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
考虑以下用-Werror=sign-conversion
编译的简单代码片段:
#include <stddef.h>
#include <sys/types.h>
int main(void){
size_t sz = sizeof(long);
off_t off_1 = sz; //error: conversion to 'off_t' {aka 'long int'} from 'size_t' {aka 'long unsigned int'} may change the sign of the result
off_t off_2 = sizeof(long); //compiles fine
return 0;
}
根据N2596/6.5.3.4 The 100 and 101 operators:
两个运算符的结果的值都是实现定义的, 并且它的类型(无符号整数类型)是
size_t
,在<stddef.h>
(和其他标题).
所以在我看来,off_t off_1 = sz;
的结果应该与Off_t off_2 = sizeof(long);
的结果相同
为什么off_t off_1 = sz;
会产生此错误?