当0 == 0
函数返回 long 和 regularlong 的 sizeof() 都说 8 时,它永远不会进入 if 语句,我不知道这里还有什么问题。
声明:
long RemoteStep; // Next packet number to-be-processed
long GetLong(BYTE * Message, const SHORT Offset)
{ // Get a long from a char *
return *(long*)&(Message[Offset]);
}
调试代码:
printf("id = %d remotestep = %d n", GetLong(Packet->Message, 2), RemoteStep);
printf("id = %d remotestep = %d n", GetLong(Packet->Message, 2), RemoteStep);
printf("id = %d remotestep = %d n", GetLong(Packet->Message, 2), RemoteStep);
printf("equals = %d n", GetLong(Packet->Message, 2) == RemoteStep);
printf("sizeof = %d - %dn", sizeof(GetLong(Packet->Message, 2)), sizeof(RemoteStep));
// Process if expected
if (GetLong(Packet->Message, 2) == RemoteStep)
{
printf("in.............n");
...
}
输出信息:
id = 0 remotestep = 0
id = 0 remotestep = 0
id = 0 remotestep = 0
equals = 0
sizeof = 8 - 8
id = 1 remotestep = 0
id = 1 remotestep = 0
id = 1 remotestep = 0
equals = 0
sizeof = 8 - 8
我在compat-gcc-34-c++
又名 g++34
下编译了它,我不能使用较新的 g++ 编译器,因为它们给出了太多的警告甚至错误。
与-Wall -Wextra
declares.h:1880: warning: int format, different type arg (arg 2)
declares.h:1880: warning: int format, different type arg (arg 3)
declares.h:1880: warning: unknown conversion type character 0x20 in format
declares.h:1880: warning: unknown conversion type character 0x20 in format
declares.h:1880: warning: too many arguments for format
declares.h:1881: warning: unknown conversion type character 0x20 in format
declares.h:1881: warning: unknown conversion type character 0x20 in format
declares.h:1881: warning: too many arguments for format
declares.h:1882: warning: unknown conversion type character 0x20 in format
declares.h:1882: warning: unknown conversion type character 0x20 in format
declares.h:1882: warning: too many arguments for format
declares.h:1884: warning: int format, different type arg (arg 2)
declares.h:1884: warning: int format, different type arg (arg 3)
1880行是其中之一
printf("id = %l remotestep = %l n", GetLong(Packet->Message, 2), RemoteStep);
long
类型不应与 %d
一起打印,这在规范中明确未定义。例如
每个转换规范都由"%"字符引入...
...
如果转换规范与上述形式之一不匹配,则行为未定义。如果任何参数不是相应转换规范的正确类型,则行为未定义。 http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html
(文档适用于printf
以及fprintf
)
因此,您不能依赖 的输出,
printf("id = %d remotestep = %d n", GetLong(Packet->Message, 2), RemoteStep);
以确定
printf("equals = %d n", GetLong(Packet->Message, 2) == RemoteStep);
//output: equals = 0
实际上是不正确的,您需要先修复调试语句:
printf("id = %ld remotestep = %ld n", GetLong(Packet->Message, 2), RemoteStep);
在您的情况下,最好使用 memcpy
而不是指针转换,
long GetLong(BYTE * Message, const SHORT Offset)
{
long result;
std::memcpy(&result, &(Message[Offset]), sizeof(long));
return result;
}
因为long*
在您的平台上可以有比char*
更严格的对齐要求.
您可以将语句更改为使用 std::cout 而不是 printf,因为您使用 C++ 而不是 C 标记了问题。使用 cout,您将不会在运行时获得 %d 或其他 % 说明符的这些令人惊讶的效果。
printf("id = %d remotestep = %d n", GetLong(Packet->Message, 2), RemoteStep);
大概可以替换为
std::cout << "id = " << GetLong( Packet->Message, 2 ) << " remotestep = " << RemoteStep << " n";