Write a program that will print “C” if compiled as

2020-02-03 06:14发布

Taken from http://www.ocf.berkeley.edu/~wwu/riddles/cs.shtml

It looks very compiler specific to me. Don't know where to look for?

10条回答
该账号已被封号
2楼-- · 2020-02-03 06:54

You could try preprocessor directives, but that might not be what they are looking for.

查看更多
时光不老,我们不散
3楼-- · 2020-02-03 06:57

Simple enough.

#include <stdio.h>
int main(int argc, char ** argv) {
#ifdef __cplusplus
printf("C++\n");
#else
printf("C\n");
#endif
return 0;
}

Or is there a requirement to do this without the official standard?

查看更多
放荡不羁爱自由
4楼-- · 2020-02-03 07:02

I'm guessing the intent is to write something that depends on differences between the languages themselves, not just predefined macros. Though it's technically not absolutely guaranteed to work, something like this is probably closer to what's desired:

int main() { 
    char *names[] = { "C", "C++"};

    printf("%s\n", names[sizeof(char)==sizeof('C')]);
    return 0;
}
查看更多
我想做一个坏孩纸
5楼-- · 2020-02-03 07:04

Here's the program:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("This is %s\n", sizeof 'a' == sizeof(char) ? "C++" : "C");
    return 0;
}

And here is some nice reading on C and C++ differences.

查看更多
Viruses.
6楼-- · 2020-02-03 07:06

For what it's worth, here's another answer:

char x[sizeof(char *)+2], y[1];
printf("%.*s\n", sizeof(1?x:y)-sizeof(char *)+1, "C++");
查看更多
甜甜的少女心
7楼-- · 2020-02-03 07:10

Just look to see if the __STDC__ and __cplusplus compiler macros are defined.

查看更多
登录 后发表回答