Method parameters (void) vs no void declare (error from the compiler)

Why does the compiler give an error in this case, method declarations -

-(void) someMethod (void); 

But I approve it -

  -(void) someMethod; 

(SomeClass.h)

I read that it is better to declare (void) in parameters than not to declare, but maybe I missed some point.

+4
source share
2 answers

You cannot do this for Objective-C.

In Objective-C, each parameter must be after : for example.

 - (void)someMethod:(int)i; - (void)someMethod:(int)i withString:(NSString *)string; - (void)someMethod:(int)i :(int)i2 :(int)i3; // you can do this but is bad style 

and it makes no sense to do something like

 - (void)someMethod:(void)what_goes_here; 

therefore, if you want to use a method without a parameter:

 - (void)someMethod; 

However you can do it in C / C ++

 void someMethod(void); 

And I did not see any benefit from declaring void parameters (explicitly declaring things is not always good).

+10
source

@Xlc answer extension

The answer is the syntax difference between Objective-C and "normal" C / C ++.

Returning to the origins of the Unix and C days, in the late 60s / early 70s, declaring (not defining) a function, you did not need to indicate how many arguments it took, or what types they should have been. Also, you did not need to indicate whether it returned a value.

Later, people realized that this would be a good idea, both for better detection of errors during compilation, and for greater efficiency of the generated code. Thus, developers have added the ability to specify argument types in a function declaration. This was standardized as part of ANSI C in the late 80s.

However, it was necessary to maintain backward compatibility with existing code. Thus, the declaration of the function foo() cannot be considered a “function without arguments”. To solve this problem, the void keyword was introduced. This allowed you to say foo(void) as "a function named foo that takes no arguments."

When Objective-C was invented in the 90s, they added new syntax for defining methods. Since there was no deprecation code, they simply said that the method should declare all its arguments; if there are none, then the method takes no arguments.

Objective-C still uses the void keyword to indicate that the method does not return any value.

+4
source

Source: https://habr.com/ru/post/1497559/


All Articles