%x printf说明符的类型是否为long OK?

问题描述

我在Win32 docs上找到了它:

// Check the smart card context handle.
// hContext was set prevIoUsly by SCardEstablishContext.

LONG    lReturn;
lReturn = SCardisValidContext(hContext);
if ( SCARD_S_SUCCESS != lReturn )
{
   // Function Failed; check return value.
   if ( ERROR_INVALID_HANDLE == lReturn )
       printf("Handle is invalid\n");
   else
   {
       // Some unexpected error occurred; report and bail out.
       printf("Failed SCardisValidContext - %x\n",lReturn);
       exit(1);  // Or other appropriate error action.
   }
}
else
{
   // Handle is valid; proceed as needed.
   // ...
}

printf("Failed SCardisValidContext - %x\n",lReturn);行正在将LONG类型的参数(long的typedef)传递给printf,其中printf期望unsigned int根据cppreference.com。这是定义明确的行为吗?如果是这样,是否与对static_cast的显式unsigned int相同?

解决方法

%x printf说明符的类型是否为long OK?

否,在C ++中不正确。 %x用于无符号整数,时间不长。

这种行为是否明确定义?

否,这是不确定的行为。引用C标准草案(在其中定义格式说明符的地方):

x,X 无符号int参数被转换为...无符号十六进制表示法...

如果任何参数都不是相应转换规范的正确类型,则行为是不确定的。


如果系统记录在Windows中,可能在Windows中是“ OK”,但依靠这种保证将无法移植到其他系统。我怀疑该示例并非旨在证明这种滥用格式说明符的有效性,而是偶然的。

,

printf("%x",(LONG)101);在Windows中是有效且定义良好的 ,其中LONGdefined,是' 32位带符号整数 ”,与int相同,大小与unsigned int相同。

使用C ++类型的可移植等效项为printf("%lx",(unsigned long)101l);