9

I googled for this, and was surprised to find no guidelines, rules of thumb, styles, etc. When declaring a (signed or not signed) integer in C, one can make the choice to just use whatever the processor defines for int, or one can specify the width (e.g. uint16_t, int8_t, uint32_t, etc).

When doing desktop/dedicated C programs, I've tended very much towards the "just use the defaults" unless it was really important for me to specify width (e.g. "this is a 32 bit ID").

Having done more microcontroller work lately (pic18 and AVR), I've tended to size everything, just because you become so space conscience.

And now I'm working on some Pic32 code (no OS), where I find myself torn between the two extremes.

I'm curious what rubric (if any) people have formulated that help them decide when to size their ints, and when to use the defaults? And why?

4

3 回答 3

6

如果某件事对您很重要,请尝试使其尽可能明确。
如果你真的不在乎,让编译器决定。

这和你自己写的很接近。如果您必须遵循规范,即 32 位,请使用大小类型。如果它只是一个循环计数器,请使用int.

于 2013-07-16T18:51:44.827 回答
2

There actually is a guideline that mentions this. MISRA C has a rule that says you should always use sized types. But the rule is only advisory, not required or mandatory for compliance.

From here:

6.3 (adv): 'typedefs' that indicate size and signedness should be used in place of the basic types.

于 2013-07-17T12:56:07.470 回答
2

你应该同时使用两者。

Misra 规则很好,但并不适用于所有地方。

使用大小类型更适合跨平台编译,例如在 pc 平台上模拟嵌入式软件。

但即便如此,您也需要printf根据大小类型来考虑大小。

uint32_t val;

printf("%d", val);
printf("%ld", (long)val);

第一个printf适用于许多 32 位平台,但在许多 int=16bit/long=32bit 的嵌入式平台上失败。

uint16_t len = strlen("text");

可以产生警告,因为 strlen 的返回类型是int并且int可以大于uint16_t,这里最好使用int len.

于 2013-07-18T09:45:54.210 回答