Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#if vs #ifndef vs #ifdef

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.

like image 772
amanuel2 Avatar asked May 07 '16 19:05

amanuel2


1 Answers

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

will expand to

#if Compare == 011x101

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.

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

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.

like image 115
463035818_is_not_a_number Avatar answered Oct 07 '22 04:10

463035818_is_not_a_number