C Unsigned int提供负值? [英] C Unsigned int providing a negative value?

查看:106
本文介绍了C Unsigned int提供负值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无符号整数,但当我用%d打印出来时,有时会出现负值吗?

I have an unsigned integer but when i print it out using %d there is sometimes a negative value there?

推荐答案

打印%d 将读取整数作为带符号的十进制数,无论其定义的类型如何。

Printing %d will read the integer as a signed decimal number, regardless of its defined type.

打印无符号数字,使用%u

To print unsigned numbers, use %u.

这是因为C处理变量参数的方式。编译器只是从堆栈中提取值(键入 void * 并指向调用堆栈)并且 printf 必须从你给它的格式字符串中找出数据包含的内容。

This happens because of C's way to handle variable arguments. The compiler just pulls values from the stack (typed as void* and pointing to the call stack) and printf has to figure out what the data contains from the format string you give it to.

这就是你需要提供格式字符串的原因 - C无法 RTTI 或基类(对象 in例如,Java从中获取通用或预定义的 toString

This is why you need to supply the format string - C has no way of RTTI or a 'base class' (Object in Java, for example) to get a generic or predefined toString from.

这篇关于C Unsigned int提供负值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆