2014-10-19 169 views
1
#include <stdlib.h> 
#include <stdio.h> 

#define SIZE_TYPE 
#define MEM_SIZE_BYTES 4096 
#define MEM_SIZE_WORDS MEM_SIZE_BYTES/sizeof(int) 

int main() { 

    printf("bytes are %d\n", MEM_SIZE_BYTES); 
    printf("words are %d\n", MEM_SIZE_WORDS); 

} 

汇编给出警告......为什么?为什么此代码会发出警告?

testintsize.c:11:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat] 

我在这里找到了SIZE_TYPE宏:https://gcc.gnu.org/onlinedocs/gccint/Type-Layout.html 是与此相关的是。

这样做并没有引起报警消失:

#define SIZE_TYPE int 
+2

'sizeof'运算符返回一个'size_t'类型的值,它必须是无符号的,并且足够大以适应平台上所有可能的大小,并且在您的特定平台上是'unsigned long int',您需要'“%lu”'格式。参见例如[这个'printf'参考页面](http://en.cppreference.com/w/c/io/fprintf)。 – 2014-10-19 05:25:40

+0

SIZE_TYPE宏有什么作用? – abc 2014-10-19 05:34:36

+0

编译器可能会检查它是否有'size_t'的定义。定义它可能会导致奇怪的事情发生。 – 2014-10-19 05:38:27

回答

2

你要解决此警告几种不同的方式:

选项#1:

#define MEM_SIZE_WORDS MEM_SIZE_BYTES/sizeof(int)  // change this 
#define MEM_SIZE_WORDS MEM_SIZE_BYTES/(int)sizeof(int) // to this 

选项#2:

#define MEM_SIZE_WORDS MEM_SIZE_BYTES/sizeof(int)  // change this 
#define MEM_SIZE_WORDS (int)(MEM_SIZE_BYTES/sizeof(int)) // to this 

选项#3:

printf("words are %d\n", MEM_SIZE_WORDS); // change this 
printf("words are %lu\n", MEM_SIZE_WORDS); // to this 
+0

-1,这不是问题的答案,而且还提供了错误的解决方案。 – 2014-10-19 15:57:51

+0

@JensGustedt:阅读这个问题,你是挑剔的。 OP了解这个问题,并且正在寻找解决方案。 – 2014-10-19 16:08:46

+0

C标准预见的真正解决方案是使用'%zu'作为格式说明符。 – 2014-10-19 16:12:17

2

在这种情况下,的sizeof返回一个长UNSIGNED INT。一种办法来解决警告:

#include <stdlib.h> 
#include <stdio.h> 

#define SIZE_TYPE 
#define MEM_SIZE_BYTES 4096 
int intSize = sizeof(int); 
#define MEM_SIZE_WORDS MEM_SIZE_BYTES/intSize 

int main() { 

    printf("bytes are %d\n", MEM_SIZE_BYTES); 
    printf("words are %d\n", MEM_SIZE_WORDS); 

} 

intSize是全球变量。在某些情况下,这不会被视为最佳做法。使用强制转换为int将优于(请参阅barak的评论和答案)。

+1

每次使用'MEM_SIZE_WORDS'时,这将产生一个运行时计算。 – 2014-10-19 05:36:14

+0

什么是#define SIZE_TYPE宏在这里做什么? – abc 2014-10-19 05:37:09

+0

嗨@barak,自从我写上我最后的C代码以来,这已经过去了。在预编译器编译之前,MEM_SIZE_BYTES/intSize会被计算一次吗?此时,MEM_SIZE_WORDS将被结果值简单地替换。也就是说,在运行时不需要重新计算。 – 2014-10-19 05:46:04

0

sizeof运算符返回类型size_t这是一个无符号整数类型。由C的隐式类型转换规则MEM_SIZE_BYTES/sizeof(int)也具有相同的类型,size_t

要打印该类型的值,请使用%zu作为printf格式。

相关问题