Is objective C 2.0 a proper superset of C?

雨燕双飞 提交于 2019-12-17 17:00:31

问题


I've heard that objective-C is a proper superset of C, but is objective-C 2.0?

The reason I ask is that either it isn't, or I misunderstand the phrase 'proper superset', because this code is valid C syntax:

#import <stdio.h>

int main () {
    char *nil = "hello";
    printf("%s\n",nil);
}

But does not compile in Objective-C 2.0. Obviously, this is an easily fixable problem, but I'm writing a paper, and feel that this is something that should be pointed out.


回答1:


nil is not a keyword. nil is defined in objc.h [on Mac OS X] (and __DARWIN_NULL is really just NULL):

#ifndef nil
#define nil __DARWIN_NULL   /* id of Nil instance */
#endif

That is, nil isn't really part of the compiled language, but a convention used during compilation that is perpetuated by the system libraries.

Splitting hairs, obviously. You really could compile Objective-C source without nil, though.

It is akin to asking "Can I write a tool that has variables named deflate while still using the zlib.h interface?". Sure. But it'll be ugly.

And, in fact, the compiler does not automatically include objc.h. This:

#include <stdio.h>

int main() {
    int nil = 5;
    fprintf(stdout, "Hello %d\n", nil);
    return 0;
}

Compiles and runs just fine in a standard Foundation tool project (in the main.m) once you remove the precompiled/prefix header that imports Foundation and, hence, objc.h. (So, yes, out of the box, the Xcode templates do cause objc.h to be imported by way of importing Cocoa/Cocoa.h or Foundation/Foundation.h.)




回答2:


Objective-C a proper superset of C, as everything that works in C will work with Objective-C.

BUT,

as it is a superset, it adds some new types, definitions and directives.

That means that if you use a reserved definition like nil, you are getting into serious trouble.

That's why the above program does not compile.



来源:https://stackoverflow.com/questions/2963832/is-objective-c-2-0-a-proper-superset-of-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!