NVIDIA Interview Question
#define is a preprocessor. it doesn't take any area inside the program memory. Before compilation it replace with the actual value inside the code.
Yes deestiny. my explanation for the code is wrong .. however, output is correct..
The correct reason is.. preprocessor scans the code from beginning and replaces all the statements followed by a #define statement with the corresponding value..
g()
{
#define b 6
}
int main()
{
g();
f();
printf("%d",b);
return 0;
}
f()
{
#define b 4
}
Now.. the b value in main() is 6..
If you remove the call to method g(), then also output will be 6, as preprocessor doesnt care the execution sequence.. It just scans the files executing the preprocessor statements..
Answer is compilation error.
so how does it work and where is it stored. pre-processor parses and does textual replacement of the value. So the value is nothing but some constant, it is stored in global/static area and the type used will be based on the value.
to some of the people ho had doubt abut why it prints 4 at one place and 6 at other place bcoz pre-processor would have substituted so and when it comes to compilation stage the values are already substituted and these values will be then stored in global/static area.
macro.c: In function ‘main’:
On Ubuntu9.10
gcc marco.c -o marco
macro.c:5: error: ‘x’ undeclared (first use in this function)
macro.c:5: error: (Each undeclared identifier is reported only once
macro.c:5: error: for each function it appears in.)
macro.c:3: warning: return type of ‘main’ is not ‘int’
It will give a syntax error as "x undeclared" .. The preprocessor replaces all the statements followed by the #define statements within the scope..
- Teja October 24, 2009This will work without any error-
void main()
{
#define x 1
funct();
}
funct()
{
printf("%d",x);
}
whereas this will give an error-
void main()
{
funct();
printf("%d",x);
}
funct()
{
#define x 1
}