无符号整型算术 - C 初学者

发布于 2024-12-16 12:22:28 字数 446 浏览 4 评论 0原文

冒着因发布一个愚蠢问题而被骂的风险:

假设我有以下代码片段:

unsigned int limit = 4294967296;
int math = 50000;

while(limit > 50000)
{
    limit = limit - math;
    printf("new limit is - \t%u\n", limit);
}

在 unsigned int 类型和 int 类型之间进行算术会对内存使用产生影响吗?

我知道 unsigned int 的内存要多一个数量级(int 为 2^31,unsigned int 为 2^32),但是,由于我使用 unsigned int 作为占位符,所以我认为我正在否定溢出的危险。

我会自己运行这个,但我现在没有可访问的 Linux 盒子。

对此的任何意见将不胜感激。

At the risk of getting yelled at for posting a stupid question:

say I have the following code snippet:

unsigned int limit = 4294967296;
int math = 50000;

while(limit > 50000)
{
    limit = limit - math;
    printf("new limit is - \t%u\n", limit);
}

Would doing arithmetic between an unsigned int type and an int type have rammifications o n memory usage?

I know that an unsigned int has an order of magnitude more memory (2^31 for an int vs 2^32 for an unsigned int), but, since I'm using my unsigned int as a placeholder, i think I'm negating the danger of an overflow.

I would run this myself, but I don't have an accessible linux box right now.

Any input on this would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜血缘 2024-12-23 12:22:28

这将永远循环,因为您最终将得到环绕(即 limit 永远不会小于 0)...这是您的问题吗?

This will loop forever since you will end up with wrap-around (i.e., limit will never be less than 0) ... is that your question?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文