Solved

Just-for-fun II

Posted on 1998-08-25
2
205 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
  • 2
2 Comments
 
LVL 11

Accepted Solution

by:
alexo earned 0 total points
Comment Utility
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
Comment Utility
Did I?  It's hard to tell with 0 points ;-)
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

744 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now