Is this valid?

M

Michael

Hi i recently came across some code that looked like this which I've never
ever seen before! I appreicate it may be 'c' but is it valid in c++??


//main.c

int main()
{
int a;
int b;
//Get values for a & b;

if(a==1)
{
#include "DoA.c"
}
else
{
#include "DoB.c"
}

// More stuff


return 0;
}


//DoA.c
b =4;


//DoB.c
b=6;



Is this valid? Or just obscure?
 
I

Ioannis Vranos

Michael said:
Hi i recently came across some code that looked like this which I've never
ever seen before! I appreicate it may be 'c' but is it valid in c++??


//main.c

int main()
{
int a;
int b;
//Get values for a & b;

if(a==1)
{
#include "DoA.c"
}
else
{
#include "DoB.c"
}

// More stuff


return 0;
}


//DoA.c
b =4;


//DoB.c
b=6;



Is this valid? Or just obscure?


It is valid.
 
M

Matt Wharton

Michael said:
Hi i recently came across some code that looked like this which I've never
ever seen before! I appreicate it may be 'c' but is it valid in c++??


//main.c

int main()
{
int a;
int b;
//Get values for a & b;

if(a==1)
{
#include "DoA.c"
}
else
{
#include "DoB.c"
}

// More stuff


return 0;
}


//DoA.c
b =4;


//DoB.c
b=6;



Is this valid? Or just obscure?

Yes, it's valid. Yes, it's obscure (and entirely unnecessary in the example
you posted).

-Matt
 
M

Michael

in that case, does #include mean copy contents of file here ( with the
absence of pragma's)?
 
J

Jonathan Turkanis

Michael said:
in that case, does #include mean copy contents of file here ( with the
absence of pragma's)?

It means exactly the same thing as it does when used at the beginning of a file.
The preprocessor knows nothing about control structures such as if ( ) { }else
{ }, and so has no idea that headers are being #include'd in unusual places.

The ability to #include headers in the middle of a block of code is very useful
for preprocess metaprogramming (see
http://boost-consulting.com/tmpbook/preprocessor.html)

Jonathan
 
I

Ioannis Vranos

Michael said:
in that case, does #include mean copy contents of file here ( with the
absence of pragma's)?


#includes are processed by the preprocessor before the compilation. In
the final source code that gets compiled, the #includes have been
replaced by the text that they include.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top