Solved

Just-for-fun II

Posted on 1998-08-25
2
238 Views
Last Modified: 2010-04-01
int plainc(void)
{
  switch (2 //**/ 2
         ) {
    case 2: return 0; /* actually C++ */
    default: return 1; /* plain C */
   }
}

Has anybody got another function which is valid in both languages that does the same job?
0
Comment
Question by:JYoungman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 11

Accepted Solution

by:
alexo earned 0 total points
ID: 1171175
This only works if the C compiler is strict ANSI and does not treat "//" as a valid comment delimiter (a common extension).

However, Struostrup says (B.2.1) "ISO C is being revised to allow // as in C++" thus invalidating the technique.

A similar (and more readable) technique that is guaranteed to work is:

    int plainc(void) { return sizeof('a') == sizeof(int) ? 1 : 2; }

And a slightly more obscure one:

    int plainc(void)
    {
        int x;
        {
            struct x { int a, b; };
            return sizeof(x) == sizeof(int) ? 1 : 2;
        }
    }

And the most portable is, of course:

    int plainc(void)
    {
    #ifdef __cplusplus
        return 2;
    #else
        return 1;
    #endif
    }

Do I get an 'A' ?
0
 
LVL 11

Expert Comment

by:alexo
ID: 1171176
Did I?  It's hard to tell with 0 points ;-)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question