Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Just-for-fun II

Posted on 1998-08-25
2
Medium Priority
?
246 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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

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…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

604 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