如何确定我是否过度括号? [英] How can I determine if I'm overparenthesizing?
问题描述
我目前正在尝试避免在C语言中使用指针算术来编写模拟器。
I'm currently trying to avoid the pointer arithmetic workings in C to write an emulator.
通常,如果您添加 1
到C中的指针,则改为添加指向对象的大小。但是,我试图使用位和字节,所以这是不希望的。
Usually, if you add 1
to a pointer in C, you add the size of the pointed to object instead. However, I am trying to work with bits and bytes, so this is undesired.
我想知道在此示例中是否使用了太多的括号:
I was wondering if I was using too many parentheses in this example:
*(int16_t *)(((intptr_t)bc)+sp)
如果不是,那么是否等同于此? :
And if not, then is it equivalent to this? :
*(int16_t *)((intptr_t)bc+sp)
sp
是我的模拟器的页面对齐堆栈地址(通过 mmap
(未设置 MAP_FIXED
)。这是 intptr_t
类型。
sp
is a page-aligned stack address for my emulator (obtained via. mmap
without MAP_FIXED
set). It is an intptr_t
type.
bc
是 int16_t *
类型的名称。这是两个 int8_t
的组合的指针。
bc
is the name of an int16_t *
type. It's a pointer to a combination of two int8_t
's.
推荐答案
((((intptr_t)bc)+ sp)
等同于((intptr_t)bc + sp)
。
但这整个避免指针算术方法是不可移植的。
But this whole "avoid the pointer arithmetic" approach is not portable.
至少3个关注点:
-
指针,转换为
Pointers, converted to an integer, do not certainly maintain the math properties needed.
// possible outcome
uint16_t x[2];
printf("%llx\n", (unsigned long long) (intptr_t) &x[0]); // --> abcd0000
printf("%llx\n", (unsigned long long) (intptr_t) &x[1]); // --> abcd0010
作为整数的差可能是16和不是2的希望-即使相差2更常见。
The difference as integers may be 16 and not the hoped for 2 -- even if a difference of 2 is more common.
-
进一步,其中
*(int16_t *)((intptr_t)bc + sp)
,如果sp
是奇数,则(int16_t *)
可能由于对齐限制而失败。
Further, with
*(int16_t *)((intptr_t)bc+sp)
, ifsp
is odd,(int16_t *)
can fail due to alignment restrictions.
也出现了抗锯齿问题。 @Andrew Henle
Anti-aliasing issues occur too. @Andrew Henle
尽管整数有各种陷阱,但还是避免了指针算术-祝你好运。
Such avoidance of pointer arithmetic though integers has various pitfalls - good luck.
这篇关于如何确定我是否过度括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!