是否有一种直观的方式检查标志和状态
Is there an intuitive way of checking for flags and states?
无法找到我案件的相关答案,因此我将尝试解释我的情况:
我有以下代码:
enum Flags {
OnlySpaces = 1 << 0,
valComment = 1 << 1,
valCommentBlock = 1 << 2,
valLabelName = 1 << 3,
valVariableName = 1 << 4,
valFunctionName = 1 << 5,
invSyntax = 1 << 32,
fInVarLab = valLabelName|valVariableName,
fInIdentifier = valLabelName|valVariableName|valFunctionName,
fInCommentBlock = OnlySpaces|valCommentBlock,
initState = OnlySpaces|fInIdentifier|valComment,
};
int lexStatus = initState;
for (int i = 0; sc.More(); sc.Forward(), i++) {
if (sc.atLineStart) {
if (lexStatus & fInCommentBlock != fInCommentBlock) // Here is the problem
sc.SetState(DEFAULT);
lexStatus = initState;
}
... // More code
}
我的代码是为了征求文档,我只有在不在评论块中时才能做一个操作。问题是,当我不在评论中,上述语句完全返回相反的情况...
以下语句正确地完成了工作,但似乎违反直觉:
if (lexStatus & fInCommentBlock == fInCommentBlock)
所以问题是:
- 为什么?为什么它的行为与我的期望完全相反?
由于操作员优先级,if ((lexStatus & fInCommentBlock) != fInCommentBlock)
解决了问题
- 我正在以正确的方式接近吗?
- 有更好的方法吗?
- 有没有办法确保每个标志具有独特的值?
添加了最后一个问题,因为出于某种原因lexStatus & fInCommentBlock
,因为设置了某些位,即使我不在代码中的任何地方设置它们...
预先感谢您的帮助!
解决您的第一个问题:您的问题是操作员的优先级和对位运算符的工作方式的理解。
if (lexStatus & fInCommentBlock == fInCommentBlock)
这仅是因为==
比&
具有更高的优先级,因此fInCommentBlock == fInCommentBlock
始终是正确的,因此与lexStatus & 1
相同,这与lexStatus & OnlySpaces
是相同的。当lexStatus == initState
时,这将是正确的,因为initState
包括标志OnlySpaces
。
有更好的方法吗?
您想将位比较抽象为一个或两个辅助功能。
int LexStatus_Is(int flags) { return (lexStatus & flags) == flags; }
int LexStatus_IsNot(int flags) { return (lexStatus & flags) != flags; }
然后您可以写:
if (LexStatus_IsNot(fInComment))
更直观。
相关文章:
- 如何以更有效的方式检查一个数字是否是素数?
- 提升图形库:以高性能的方式检查vertex_descriptor的有效性
- C++ Windows - 以编程方式检查软件是否访问互联网?
- 使用 python 绑定来检查 C++ 类型是否是规范方式的指针、引用等?
- 统一检查成员函数、自由函数和算子是否存在的方式
- C++ Qt - 检查 Steam 游戏是否以编程方式运行
- 如何使用 gdb 调试 LLVM 检查器时以图形方式查看 CFG
- 如何通过使用C,C 在Linux上指定其名称,以编程方式检查特定的守护程序
- 是否有一种直观的方式检查标志和状态
- 不同的条件检查方式
- 以编程方式检查字节序
- 通过办公自动化或其他方式检查MS Office许可证状态
- 如何以可移植的方式检查文件是否存在于C++中
- 如何使用C/C++以编程方式检查窗口中的系统文件夹
- 以编程方式检查年份是否更改的最有效方法
- 以编程方式检查应用程序正在使用的内核数量
- 是否可以在 Windows C++ 中以编程方式检查我的笔记本电脑是通过 Wi-Fi 还是通过"wired LAN"连接的?
- 如何以编程方式检查Windows Server 2016上是否安装了桌面体验
- 以一种漂亮的STL方式检查一个范围是否是另一个范围的子范围
- 如何以最快的方式检查两个给定位置之间是否存在一个数字