2014-01-13 70 views
1

有人可以解釋我爲什麼常量不匹配if()條件中的變量?常量與變量不匹配

z3 tests # cat deftst.c 
#define _GNU_SOURCE 
#include <stdio.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <sys/ioctl.h> 
#include <linux/fs.h> 
#include <fcntl.h> 

#define MY_BLOCK_SIZE    512 

main() { 
     int fd,ret; 
     size_t block_size; 

     fd=open("/dev/loop2",O_DIRECT|O_RDWR|O_NONBLOCK); 
     printf("fd=%d\n",fd); 

     ret = ioctl(fd, BLKSSZGET, &block_size); 
     printf("ret=%d\n",ret); 
     if (block_size!=MY_BLOCK_SIZE) { 
       printf("block_size=%d , MY_BLOCK_SIZE=%d\n",block_size,MY_BLOCK_SIZE); 
       printf("error, block size don't match the constant!\n"); 
     } 
} 
z3 tests # gcc -o deftst deftst.c 
deftst.c: In function 'main': 
deftst.c:21:3: warning: format '%d' expects type 'int', but argument 2 has type 'size_t' 
z3 tests # dd if=/dev/zero of=device.dat bs=512 count=128 
128+0 records in 
128+0 records out 
65536 bytes (66 kB) copied, 0.00167074 s, 39.2 MB/s 
z3 tests # losetup /dev/loop2 device.dat 
z3 tests # ./deftst 
fd=3 
ret=0 
block_size=512 , MY_BLOCK_SIZE=512 
error, block size don't match the constant! 
z3 tests # 

我試着用十六進制打印,並確認它是相同的值,在常量和變量中。這樣的奇怪的事情。

+1

編譯器給你一個警告。 – devnull

+1

@devnull刪除printf()行,您將不會收到警告,但會得到相同的結果 – Nulik

+1

@Nulik但是,如果使用正確的格式說明符,則「printf」實際上會顯示正確的值,這有助於診斷問題。 – interjay

回答

3

看來BLKSSZGET期望一個指向int的指針,你的block_size可能很長。見here