Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of #define preprocessor in C

Tags:

The scope of #define is till the end of the file. But where does it start from. Basically I tried the following code.

 #include<stdio.h>  #include<stdlib.h>  #define pi 3.14  void fun();  int main() {  printf("%f \n",pi);  #define pi 3.141516     fun(); return 0; } void fun(){ printf("%f \n",pi);} 

The output of the above program comes out to be

3.140000 3.141416 

Considering preprocessing for main the value of pi should be 3.141516 and outside main 3.14. This is incorrect but please explain why.

like image 307
Rohit Jain Avatar asked Jun 16 '11 22:06

Rohit Jain


People also ask

What does within the scope of mean?

the range of things that an activity, company, law, etc. deals with: large/ambitious in scope. beyond/outside the scope of sth He involved himself in affairs beyond the scope of his job. within the scope of sth To come within the scope of the law of confidence, the information does not have to be particularly special.

What is meant by scope and example?

Scope is range of understanding, thought or action. An example of scope is someone having the ability to run a marathon.

What does scope of the job mean?

A scope of work is a description of the work you will do on a project for a client or employer. It lays out what will be done, who will do it, when it will be done, and how it will be evaluated.

What is scope of any subject?

Answer: The scope of a study explains the extent to which the research area will be explored in the work and specifies the parameters within the study will be operating. Basically, this means that you will have to define what the study is going to cover and what it is focusing on.


1 Answers

The C preprocessor runs through the file top-to-bottom and treats #define statements like a glorified copy-and-paste operation. Once it encounters the line #define pi 3.14, it starts replacing every instance of the word pi with 3.14. The pre-processor does not process (or even notice) C-language scoping mechanisms like parenthesis and curly braces. Once it sees a #define, that definition is in effect until either the end of the file is reached, the macro is un-defined with #undef, or (as in this case) the macro is re-defined with another #define statement.

If you are wanting constants that obey the C scoping rules, I suggest using something more on the lines of const float pi = 3.14;.

like image 102
bta Avatar answered Dec 17 '22 01:12

bta