Solved

Just-for-fun II

Posted on 1998-08-25
2
233 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
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
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 viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

730 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