1

In C#, if preprocessor directives are instructions pre-processed before actual compilation then why is it not executed first in this program?

static void Main(string[] args) { Program1.display(); Program2 p2 = new Program2(); p2.show(); #if DEBUG Console.WriteLine("DEBUG from preprocessor directive is working!"); #endif } 

Expected Output:

DEBUG from preprocessor directive is working! .......(from display()) .......(from show()) 

But Actual Output:

.......(from display()) .......(from show()) DEBUG from preprocessor directive is working! 
2
  • But code will run line by line Commented Oct 20, 2016 at 16:44
  • 8
    Preprocessor directives are instructions to the compiler about how to compile the program. They do not have any bearing on code execution order. Commented Oct 20, 2016 at 16:47

2 Answers 2

6

The output you are expecting is wrong.

Code processed (to be compiled) in DEBUG mode/configuration

static void Main(string[] args) { Program1.display(); Program2 p2 = new Program2(); p2.show(); Console.WriteLine("DEBUG from preprocessor directive is working!"); } 

Code processed (to be compiled) in non-DEBUG mode/configuration

static void Main(string[] args) { Program1.display(); Program2 p2 = new Program2(); p2.show(); } 

Hope this clears your confusion that preprocessors don't decide execution order.

Sign up to request clarification or add additional context in comments.

Comments

3

C# Language Specification, Section2.5

The pre-processing directives provide the ability to conditionally skip sections of source files, to report error and warning conditions, and to delineate distinct regions of source code. The term “pre-processing directives” is used only for consistency with the C and C++ programming languages. In C#, there is no separate pre-processing step; pre-processing directives are processed as part of the lexical analysis phase


Pre-processing directives are not tokens and are not part of the syntactic grammar of C#. However, pre-processing directives can be used to include or exclude sequences of tokens and can in that way affect the meaning of a C# program

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.