gpt4 book ai didi

c - 三元运算符作为 C 宏中三元运算符的操作数

转载 作者:太空宇宙 更新时间:2023-11-04 04:02:50 24 4
gpt4 key购买 nike

我正在尝试实现 Erathostenes 筛法以获取 unsigned long 数组的素数位,因此我编写了一个宏来检查特定位的值..(函数会更容易,但它学校作业所以它必须是宏)我需要测试索引是否在位范围内,所以有函数调用 FatalError,它是 void function with exit(1) 调用,所以逗号运算符使整个宏可能在条件内

#define GetBit(array_name, index) \
(((index) < (array_name)[0]) && ((index) >= 0)) ? \
(((array_name)[((index) / BYTE) + 1] & ( (unsigned long)1 << \
((index) % BYTE))) ? 1 : 0) : \
(FatalError("Index %ld out of range 0..%ld\n", (long)(index), \
(long)(array_name)[0]), 0)

更具可读性的形式:

#define GetBit(array_name, index) \
(range check) ? \
((bit shift, and) ? 1 : 0) : \
(function call, 0)

array_name[0] 上,有数组的大小(以位为单位)。

所以我的问题是,即使是第一个索引也无法通过范围检查,Sieve 从索引 2 开始,程序立即结束

~ $ gcc primes.c fatalerror.c -pedantic -Wall -g -std=c99 -lm; ./a.out
FATAL ERROR: Index 2 out of range 0..1000
~ $

最佳答案

嗯,看来问题出在 Erathostenes 函数中

if( ! GetBit(pole, m) )

! 宏当然扩展为,

!(range check) ? op1 : op2

所以条件被否定

我去掉了感叹号,切换了op1的返回操作数

((shift, and) ? 0 : 1)

乍一看这些值似乎有点不合逻辑,但工作得很好

感谢大家的宝贵时间

关于c - 三元运算符作为 C 宏中三元运算符的操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9749299/

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