What do curly braces inside a function's argument list mean in C? [duplicate] - objective-c

This code:
#include <stdio.h>
int main()
{
void (^a)(void) = ^ void () { printf("test"); } ;
a();
}
Compile without warning with clang -Weverything -pedantic -std=c89 (version clang-800.0.42.1) and print test.
I could not find any information about standard C having lambda, also gcc has it's own syntax for lambda and it would be strange for them do this if a standard solution existed.

This behavior seems to be specfic to newer versions of Clang, and is a language extension called "blocks".
The Wikipedia article on C "blocks" also provides information which supports this claim:
Blocks are a non-standard extension added by Apple Inc. to Clang's implementations of the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages. Blocks are supported for programs developed for Mac OS X 10.6+ and iOS 4.0+, although third-party runtimes allow use on Mac OS X 10.5 and iOS 2.2+ and non-Apple systems.
Emphasis above is mine. On Clang's language extension page, under the "Block type" section, it gives a brief overview of what the Block type is:
Like function types, the Block type is a pair consisting of a result value type and a list of parameter types very similar to a function type. Blocks are intended to be used much like functions with the key distinction being that in addition to executable code they also contain various variable bindings to automatic (stack) or managed (heap) memory.
GCC also has something similar to blocks called lexically scoped nested functions. However, there are some key differences also note in the Wikipedia articles on C blocks:
Blocks bear a superficial resemblance to GCC's extension of C to support lexically scoped nested functions. However, GCC's nested functions, unlike blocks, must not be called after the containing scope has exited, as that would result in undefined behavior.
GCC-style nested functions also require dynamic creation of executable thunks when taking the address of the nested function. [...].
Emphasis above is mine.

the C standard does not define lambdas at all but the implementations can add extensions.
Gcc also added an extension in order for the programming languages that support lambdas with static scope to be able to convert them easily toward C and compile closures directly.
Here is an example of extension of gcc that implements closures.
#include <stdio.h>
int(*mk_counter(int x))(void)
{
int inside(void) {
return ++x;
}
return inside;
}
int
main() {
int (*counter)(void)=mk_counter(1);
int x;
x=counter();
x=counter();
x=counter();
printf("%d\n", x);
return 0;
}

Related

cmake CheckSymbolExists for intrinsic

I'd like to check for intel intrinsics such as _mm_popcnt_u32 or _mm_blendv_epi8 using cmake. However the function check_symbol_exists doesn't work properly depending on the compiler. (it works with Clang but not with GCC). Indeed it is documented
If the header files declare the symbol as a function or variable then the symbol must also be available for linking (so intrinsics may not be detected).
Is there a simple way to check for those ?
As the CMake documentation also states:
If the symbol is a type, enum value, or intrinsic it will not be
recognized (consider using CheckTypeSize or CheckCSourceCompiles).
So, try to compile a small example with the Intel intrinsic using CheckCSourceCompiles. E.g.:
include(CheckCSourceCompiles)
check_c_source_compiles("
int main() {
int tmp = _mm_popcnt_u32(0);
return 0;
}
"
HAVE_INTRINISC
)

How to write 'global' inline functions in Objective-C (using C syntax)

Assuming I'm including a header file in my precompiled header that includes a bunch of inline functions to be used as helpers wherever needed in any of the project's TUs -- what would be the correct way to write those inlines?
1) as static inlines? e.g.:
static inline BOOL doSomethingWith(Foo *bar)
{
// ...
}
2) as extern inlines? e.g.:
in Shared.h
extern inline BOOL doSomethingWith(Foo *bar);
in Shared.m
inline BOOL doSomethingWith(Foo *bar)
{
// ...
}
My intention with inlines is to:
make the code less verbose by encapsulating common instructions
to centralize the code they contain to aid with future maintenance
to use them instead of macros for the sake of type safety
to be able to have return values
So far I have only seen variant 1) in the wild.
I have read (sadly can't find it anymore) that variant 1) does not accurately move the inline function's body into the callers but rather creates a new function, and that only extern inline ensures that kind of behavior.
Skipping whether you should be inlining at all for the reasons you give, the standard way to inline in Cocoa is to use the predefined macro NS_INLINE - use it either in the source file using the function or in an imported header. So your example becomes:
NS_INLINE BOOL doSomethingWith(Foo *bar)
For GCC/Clang the macro uses static and the always_inline attribute.
Most (maybe all) compilers won't inline extern inline as they operate on a single compile unit at a time - a source file along with all its includes.
make the code less verbose by encapsulating common instructions
Non-inline functions do that as well...
to centralize the code they contain to aid with future maintenance
then you should have non-inline functions, don't you think?
to use them instead of macros for the sake of type safety
to be able to have return values
those seem OK to me.
Well, when I write inline functions, I usually make them static - that's typically how it's done. (Else you can get all sorts of mysterious linker errors if you're not careful enough.) It's important to note that inline does not affect the visibility of a function, so if you want to use it in multiple files, you need the static modifier.
An extern inline function does not make a lot of sense. If you have only one implementation of the function, that defeats the purpose of inline. If you use link-time optimization (where cross-file inlining is done by the linker), then the inline hint for the compiler is not very useful anyway.
only extern inline insures that kind of behavior.
It doesn't "ensure" anything at all. There's no portable way to force inlining - in fact, most modern compilers ignore the keyword completely and use heuristics instead to decide when to inline. In GNU C, you can force inlining using the __attribute__((always_inline)) attribute, but unless you have a very good reason for that, you shouldn't be doing it.

In Objective-C ARC, what are "BPTRs declared within extern "BCPL" blocks"?

In the Clang documentation for ARC, it says:
ARC applies to Objective-C pointer types, block pointer types, and
[beginning Apple 8.0, LLVM 3.8] BPTRs declared within extern "BCPL"
blocks.
What are these "BPTRs declared within extern "BCPL" blocks"?
It's a small in-joke.
C++ has the ability to mark identifiers with C linkage, which usually just means no name mangling of functions with the same name but different parameter signature, since C, until recently, had no concept of overloading1.
The way you specify that linkage is by surrounding the identifiers with:
extern "C" {
whatever ...
}
Now, BCPL is a language that pre-dates even C (it actually forms part of the C lineage) and its "linkage" (for want of a better word) was simply a table of addresses known as the global vector.
The author of that document you reference was simply being humorous, CLang doesn't actually provide extern "BCPL" things. You'll also notice that the current version of LLVM is 3.2 with 3.3 not due until June this year. Another indication that the author was having us on, with the LLVM 3.8 comment.
Since the intent of that sentence was simply to show how annotations (within []) work, the rest of the text was largely irrelevant.
1 With the introduction of type-generic expressions in C11, it now it has overloading of a sort, though done at compile time rather than run time.
This line is obviously taken randomly from an unknown context just to demonstrate revision markers like [beginning Apple 8.0, LLVM 3.8], and BPTRs and BCPL do not mean anything specific. Generally, BPTR means something like byte pointer.

Strange "selector mangling" in Objective-C method with Boolean arguments

I need to recover method names dynamically, via reflection calls at runtime. But get strange results for some.
My TestClass contains a method like:
- (void)testMethod6_NSRect:(NSRect)a1 int:(int)a2 int:(int)a3 bool:(Boolean)a4 {
...
}
When enumerating the above classes methods using class_copyMethodList() and fetching the method selectors via method_getName(), I get:
"testMethod6_NSRect:int:int:_Bool:"
Thus, the selector was rewritten somehow (by gcc?) to make "_Bool" from "bool". As far as I tested yet, this seems to be done only for a "bool" selector-part - if I change it to int:(int), as in:
- (void)testMethod1_int:(int)a1 int:(int)a2 int:(int)a3 int:(int)a4 {
...
}
I get the expected:
"testMethod1_int:int:int:int:"
Q:
Does anyone know the rules or a pointer to where I could find them for this "selector rewriting", or am I missing something? Is this only done for "bool"?
I also need to know if this behavior is depending on the gcc-version, osx-version or runtime library version.
I am using (gcc --version):
i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)
on a (uname -a)
10.8.0 Darwin Kernel Version 10.8.0:
The problem lies in an ugly piece of preprocessor magic in the C99 standard header <stdbool.h>:
#define bool _Bool
C99 defines a type named _Bool which behaves like C++'s bool type. The define is there to be able to use it in C but with the C++ identifier.
Solution:
#undef bool
Try using BOOL instead of Boolean

What does it mean if you put more that one static modifier before a variable?

I was just fooling around in Xcode and I discovered that the following statement compiles and it doesn't even raise a warning let alone an error:
static static static int static long static var[5];
What's up with that? Does this make it super-DUPER static? :)
All joking aside, why does the compiler permit repeating the static modifier? Is there actually a reason to allow people to do this or were the people who wrote the compiler too lazy to make this raise an error?
I'm not an Objective-C developer, but does the language allow for an arbitrary ordering of modifiers (e.g. static volatile extern)? If so, then it's probably a benign bug in the compiler that after reading a modifier ("static" in this case) returns to a state where it accepts any modifier terminal again, and will do until it encounters the variable's type. Continual static declarations wouldn't contradict any prior modifiers so it wouldn't raise any errors; so based on this I would expect volatile volatile volatile int x; to also work.
For C 2011, The following applies:
Section 6.7.1 Paragraph 2
At most, one storage-class specifier may be given in the declaration specifiers in a declaration, except that _Thread_local may appear with static or extern.
And storage class specifiers are defined as:
storage-class-specifier:
typedef
extern
static
_Thread_local
auto
register
So for C 2011, that should be illegal.
As to Objective C, I have no idea where to find a language specification, so I can't help you there.