Solved

Just-for-fun II

Posted on 1998-08-25
2
227 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: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone 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

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
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 tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

791 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