[try Beta version]
Not logged in

 
Which is better?

Jan 1, 2013 at 6:36pm
1
2
#pragma once
//code.... 


1
2
3
4
#ifndef CLASS_NAME_H
#define CLASS_NAME_H
//code....
#endif 


I use the first one because thats the way I was taught it and to me it seems more logical but I don't know the ins and out of how the preprocessor handles each one. Why is #ifndef CLASS_NAME_H used as more or less the standard and not #pragma once and how does the preprocessor handle both cases?
Last edited on Jan 1, 2013 at 6:37pm
Jan 1, 2013 at 6:57pm
See: http://en.wikipedia.org/wiki/Pragma_once#Advantages_and_disadvantages

One disadvantage of #pragma once not mentioned in the article is that with it, the include guard is not predictable. This may be of importance if your program has a large number of header files (say 500) with deeply nested nested #include directives.
Jan 1, 2013 at 6:57pm
The #ifndef method is supported by all compilers, the #pragma command is supported by only a few compilers.

From the C++11 draft standard.
16.6
Pragma directive [cpp.pragma]
1 A preprocessing directive of the form # pragma pp-tokensopt new-line
causes the implementation to behave in an implementation-defined manner. The behavior might cause
translation to fail or cause the translator or the resulting program to behave in a non-conforming manner.
Any pragma that is not recognized by the implementation is ignored.


Jan 1, 2013 at 7:04pm
So is it going to be the standard as more compilers support it? I've never had portability issues with my code but I only have ever used gcc on Unix(Linux and OS X) and the Visual Studio compiler on Windows. Would it be considered a bad habit to use #pragma once because I actually learned this way when I was doing my work placement with a huge multinational company.
Topic archived. No new replies allowed.