#if vs #ifndef vs #ifdef [英] #if vs #ifndef vs #ifdef

查看:95
本文介绍了#if vs #ifndef vs #ifdef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我的问题是理解 #ifndef #ifdef 。我还想了解 #if #ifndef #ifdef 。我知道 #if 基本上是一个if语句。例如:

My problem is first of all, understanding #ifndef and #ifdef. I also want to understand the difference between #if, #ifndef , and #ifdef. I understand that #if is basically an if statement. For example:

#include<iostream>
#define LINUX_GRAPHICS 011x101

int main(){
 long Compare = LINUX_GRAPHICS;
 #if Compare == LINUX_GRAPHICS
   std::cout << "True" << std::endl;
 #endif
}

但是其他的,尽管我读过我无法理解。它们看起来也很相似,但我怀疑它们的工作方式是否相似。将不胜感激。

But the others, although I read about them I can't comprehend. They also seem like very similar terms, but I doubt they work similarly. Help would be greatly appreciated.

推荐答案

宏由预处理器扩展,该预处理器在运行时对变量值一无所知。它仅涉及文本替换(或比较预处理器已知的符号)。您的行

Macros are expanded by the preprocessor who doesnt know anything about values of variables during runtime. It is only about textual replacement (or comparing symbols known to the preprocessor). Your line

#if Compare == LINUX_GRAPHICS

将扩展为

#if Compare == 011x101

,并且由于比较与 011x101不同,因此评估为false。实际上,我什至不能100%地确定这一点,但是重点是:您正在将预处理器指令与在运行时评估的变量混合在一起。那是胡说八道。没有预处理器指令可以代替C ++语句。

and as "Compare" is differnt from "011x101", it evaluates to false. Actually I am not even 100% sure about that, but the point is: you are mixing preprocessor directives with variables that are evaluated at runtime. That is non-sense. Preprocessor directives are not there to replace C++ statements.

对于大多数传统的宏用例来说,如今有更好的方法。如果您真的不需要使用宏,则最好不要使用它们。这使得阅读代码非常困难(例如,我不理解您代码中的宏是如何工作的,除非我真的很诚实,否则我不想知道:P),并且宏还有其他问题,可能导致非常困难在您的程序中查找错误。在使用宏之前,我建议您首先考虑是否存在更自然的C ++实现目标的方法。

For most traditional use cases of macros there are better way nowadays. If you dont really need to use macros, it is better not to use them. It makes it extremly hard to read the code (eg. I dont understand how that macros in your code work and unless I really need it honstely I dont want to know :P) and there are other problems with macros that can lead to very hard to find bugs in your program. Before using macros I would advice you to first consider if there isnt a more natural C++ way of achieving the same.

PS:

#ifdef SYMBOL
    ifdef = "if defined"
    this part of the code is excluded before the compiler even sees it
    if SYMBOL is not defined (via #define)
#endif

#ifndef SYMBOL
    ifndef = "if not defined"
    this part of the code is excluded before the compiler even sees it
    if SYMBOL is defined (via #define)
#endif

我故意写了排除,以强调它对代码可读性的不利影响。如果您在常规代码块中过度使用 #ifdef #ifndef ,将很难阅读。

I wrote "excluded" on purpose to emphazise the bad impact it has on readability of your code. If you overuse #ifdef or #ifndef inside normal blocks of code, it will be extremely hard to read.

这篇关于#if vs #ifndef vs #ifdef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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