gpt4 book ai didi

c - 测试静态变量

转载 作者:行者123 更新时间:2023-11-28 21:29:40 25 4
gpt4 key购买 nike

我正在尝试对使用静态 32 位无符号整数的函数进行单元测试。

被测函数会将无符号整数递增 1。

所以,它本质上是:

void IncrementCount() {
Spi_count++;
}

Spi_Count 变量通过将输入作为最大值进行测试时,即 0xFFFFFFFF然后,如果我期望 0x100000000 作为输出,则测试通过。如果我期望 0 作为输出,那么它也会通过。

无符号变量如何通过值 0 和 0x100000000 的测试?

最佳答案

0x100000000 不是 32 位数字。 32 位是 4 个字节,或 8 个十六进制数字。您正在尝试检查 5 个字节 (0x1 00 00 00 00),而不是 4 个。如果没有您的代码,则无法确定,但编译器可能在比较中使用较低的 4 个字节,其计算结果为 0,因此你的测试工作。

Simple coding example to reproduce the problem .

#include <stdio.h>

int main(void) {
// your code goes here
unsigned int cX=-1;

printf("%04X\n", cX);
cX++;
printf("%04X\n", cX);

// Doing an explicit test of the unsigned int to 0x100000000 evaluates to false, as expected
printf("%d\n", cX==0x1000000); // Outputs 0 (false)

// If you cast the right side down to an unsigned int, then the high order bytes are lost
// and you are essentially comparing against 0, so the comparison is a success
printf("%d\n", cX==(unsigned)0x100000000); // Outputs 1 (true)


// You can do the same thing by accident using a hidden cast by calling a function. Both
// parameters are cast down to unsigned ints for the call so the right hand side loses its
// most significant bytes, resulting in 0 again.
printf("%d\n", compare(cX, 0x100000000)); // Outputs 1 (true)


return 0;
}

int compare(unsigned x, unsigned y) {
return x==y;
}

关于c - 测试静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com