谁能帮忙解释下,今天调试的时候,windbg同学给的结果。
难道被当成指针了?
补:刚跟robin讨论了下,猜测是MS WDK编译器的解释问题,目前这是唯一靠谱的解释了。
又补:根据robin的提示,用VC试了下,CPP中值就是1,C就是4。应该就是MS C编译器的解释方式了。
Submitted by boxcounter on 2009, September 17, 11:52 AM. windows编程(R0)
谁能帮忙解释下,今天调试的时候,windbg同学给的结果。
难道被当成指针了?
补:刚跟robin讨论了下,猜测是MS WDK编译器的解释问题,目前这是唯一靠谱的解释了。
又补:根据robin的提示,用VC试了下,CPP中值就是1,C就是4。应该就是MS C编译器的解释方式了。
显然, sizeof的参数应该是 变量类型 或者 变量, 而不应该是 常量
Post by ox0spy on 2009, September 17, 8:57 PM
#1
Post by boxcounter on 2009, September 17, 10:05 PM
#2
sizeof 本来参数通常应该是 变量 或者 类型 (sizeof是关键字,行为像函数,所以我说参数)
常量的话,比如'x' ,由于ansi c 要求没有明确说明类型的都是 int
所以, ubuntu gcc 下也是 4 ,
Post by ox0spy on 2009, September 17, 11:02 PM
#3
Post by boxcounter on 2009, September 18, 10:55 AM
#4
6.5.3.4 The sizeof operator
Constraints
[#1] The sizeof operator shall not be applied to an
expression that has function type or an incomplete type, to
the parenthesized name of such a type, or to an lvalue that
designates a bit-field object.
Semantics
[#2] The sizeof operator yields the size (in bytes) of its
operand, which may be an expression or the parenthesized
name of a type. The size is determined from the type of the
operand. The result is an integer. If the type of the
operand is a variable length array type, the operand is
evaluated; otherwise, the operand is not evaluated and the
result is an integer constant.
[#3] When applied to an operand that has type char, unsigned
char, or signed char, (or a qualified version thereof) the
result is 1. When applied to an operand that has array
type, the result is the total number of bytes in the
array.73) When applied to an operand that has structure or
union type, the result is the total number of bytes in such
an object, including internal and trailing padding.
这是我从C标准的文档
http://std.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.htm
里抓出来的一段解释,里面说的是,sizeof适用于expression 和 类型,所以适用于常量。
MS的文档里解释的更狭隘一些,我不应该拿它做标准~
Post by boxcounter on 2009, September 18, 11:38 AM
#5
另附上“表达式”的解释:
表示式,亦称“表达式”,是由数字、算符、数字分组符号(如括号)、自由变量和约束变量等以能求得数值的有意义排列方法所得的组合。
约束变量在表示式中已被指定数值,而自由变量则可以在表示式之外另行指定数值。
http://zh.wikipedia.org/zh-cn/%E8%A1%A8%E8%BE%BE%E5%BC%8F
Post by boxcounter on 2009, September 18, 11:42 AM
#6
其实我现在只想说, '\\' 被认为是 int 而不是 char,所以结果是4,而且c的编译器中都应该是4
sizeof(L'\\') 不知道在windows 的cl下是什么结果(没环境...), 但ubuntu gcc 是4 , AIX 下是 2
ps: L'\\' 貌似是 multi-character, 不知道怎么定义的,这个龟速网络实在不好找资料...
pps: 也许, 你可以看下 http://blog.linux.org.tw/~jserv/archives/001876.html
Post by ox0spy on 2009, September 18, 1:22 PM
#7
Post by boxcounter on 2009, September 18, 5:48 PM
#8
L'\\' 具体是表示什么意思我现在还不知道,唯一知道的是在不同的编译器下结果不一样...
c 把'x' 认为是int , 但不会把 "123456" 当成int, 后者显然是c中的字符数组
所以, sizeof("123456") 应该那个编译器上都是 7*sizeof(char)
上次看到,说下自己的观点, 最多算一起探讨下, 谢就不必了 :-)
Post by ox0spy on 2009, September 20, 1:21 AM
#9
Post by boxcounter on 2009, September 20, 11:40 PM
#10
补充:
今天翻《C语言程序设计》,看到一句话:
“单引号中的字符表示一个整型值,.........”
原来,C语言里就是这么规定的~
多谢各位的讨论,非常感谢!
原话在书中的第一章的1.5.3,13页。
Post by boxcounter on 2009, October 9, 2:54 PM
#11