从size_t转换为int没有警告

时间:2016-07-08 01:18:39

标签: c compiler-warnings sizeof size-t

考虑这个程序:

#include <stdio.h>
int main() {
  int xr = 2;
  int ya = 3;
  size_t zu = 4;
  xr = zu;
  xr = (size_t) ya;
  xr = sizeof ya;
  return xr;
}

编译产生警告:

conversion to ‘int’ from ‘size_t’ may alter its value [-Wconversion]
   xr = zu;
        ^

但只有这个警告。由于size_tsizeof都返回无符号数据类型, 我希望看到3个警告。这是怎么回事?

2 个答案:

答案 0 :(得分:0)

cast和sizeof是C operators,而不是函数。如果您使用此示例:

#include <stdint.h>
size_t mik() {
  return 1;
}
int main() {  
  return mik();
}

您会收到预期的警告:

conversion to ‘int’ from ‘size_t’ may alter its value [-Wconversion]
   return mik();
   ^

作为运营商,唯一可以预期的警告是溢出:

char nov[UINT16_MAX];
// large integer implicitly truncated to unsigned type [-Woverflow]
uint8_t osc = sizeof nov;

或不当使用演员:

uint32_t nov = 1;

// conversion to ‘uint32_t’ from ‘int’ may
// change the sign of the result [-Wsign-conversion]
uint32_t osc = (int32_t) nov;

// conversion to ‘uint8_t’ from ‘short unsigned int’ may alter its value [-Wconversion]
uint8_t pap = (uint16_t) nov;

现在对演员的不当使用实际上也是在问题中所做的:

xr = (size_t) ya;

以下是the difference

  

如果目标类型已签名,则行为是实现定义的(其中   可能包括提出信号)

答案 1 :(得分:-1)

我会说编译器足够聪明。考虑以下计划:

  int xr = -2;
  int ya = -3;
  size_t zu = 4;
  xr = zu;
  zu = ya;  
  /* Added test case
   * A negative 'ya' when converted to size_t should change its value.
   */
  printf("zu : %zu , but is this what you expected\n",zu);
  xr = (size_t) ya;
  xr = sizeof ya;

编译给出:

gcc -Wall -Wconversion 38257604.c -o 38257604
38257604.c: In function ‘main’:
38257604.c:11:3: warning: conversion to ‘int’ from ‘size_t’ may alter its value [-Wconversion]
   xr = zu;
   ^
38257604.c:12:3: warning: conversion to ‘size_t’ from ‘int’ may change the sign of the result [-Wsign-conversion]
   zu = ya;  
   ^
38257604.c:8:7: warning: variable ‘xr’ set but not used [-Wunused-but-set-variable]
   int xr = -2;
       ^

<强>道德

在C中,您负责进行类型检查。所以最好注意

  • 类型大小
  • 值的标志,对于两种类型的相同尺寸都很重要。
  • 默认情况下,未启用默认编译器标志,例如-Wsign-conversion

当你编写涉及类型转换的语句时。