Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c++ - Should preprocessor instructions be on the beginning of a line?

A while ago I have discovered an (rather ancient) C Compiler, which scanned macros this way (Pseudo code):

 if line.startswith("#include") or line.startswith("#define"):
     ...

.. Which kind of raised the question for me where macros should really be placed, at the beginning of a line, like so:

void stuff()
{
#if defined(WIN32) || defined(_WIN32)
    ...
#else
#if defined(__GNUC__)
    ...
#else
    ...
#endif
#endif
}

Or rather like so (as that's the way I do it, for improved readability):

void stuff()
{
    #if defined(WIN32) || defined(_WIN32)
    ...
    #else
    #   if defined(__GNUC__)
    ...
    #   else
    ...
    #   endif
    #endif
}

Is the way one indents the Preprocessor code standardized, that is, no matter how i indent it, it will always work the same way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some old C compilers required that the #define (for example) be flush with the left margin:

#define FOO bar

Other C compilers required only that the # be at the left margin, so you could:

#    define FOO bar

Newer C compilers tend to accept the # after any leading whitespace:

    #define FOO bar

If you want compatibility with such older compilers, you should at least put your # in the first column. If compatibility doesn't matter, then it's up to you.

I would usually try not to embed #ifdef blocks inside functions, so the whole question of whether they should be indented mostly goes away.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...