What is _Complex? - objective-c

Reading Objective-C type encodings documentation (GCC's and Apple's pages somewhat complement each other), I stumbled upon the _Complex keyword. I've never heard about it, and when I tried to look it up, I found tons of results talking about erroneous uses of it, but never what it really did.
What is _Complex, and how does it work?

A complex number type which looks like it uses half the bit-width for the real part and half for the imaginary part:
_Complex double x; declares x as a variable whose real part and imaginary
part are both of type double.
_Complex short int y; declares y to
have real and imaginary parts of type
short int; this is not likely to be
useful, but it shows that the set of
complex types is complete.
Posts about "EXC_BAD_ACCESS _Complex double return"
http://hintsforums.macworld.com/showthread.php?t=92768
http://developer.apple.com/library/mac/#documentation/DeveloperTools/gcc-4.0.1/gcc/Complex.html

Complex numbers.

Related

Is there any reason to use NSInteger instead of uint8_t with NS_ENUM?

The general standard appears to use NS_ENUM with NSInteger as the base type. Why is this the case? Assuming less than 256 cases (which covers almost any enumeration), is there any reason to use that instead of uint8_t, which could use less memory space? Either imports into Swift fine.
This is different than NS_OPTIONS, where a larger type makes sense, since you shouldn't be doing any bit math with enumerations, and you can use every number representable by the base type as a value.
The answer to the question in the title:
Is there any reason to use NSInteger instead of uint8_t with NS_ENUM?
is probably not.
When declaring an enum in C if no underlying type is specified the compiler is free to choose any suitable type from char and the signed and unsigned integer types which can at least represent all the values required. The current Xcode/Clang compiler picks a 4-byte integer. One could reasonably assume the compiler writers made an informed choice - some balance of performance and storage.
Smaller types, such as uint8_t, will usually be aligned on smaller boundaries in memory (or on disc) - but that is only of benefit if the adjacent field matches the alignment e.g. if a 2-byte size typed field follows a 1-byte sized typed field then unless otherwise specified (e.g. with a #pragma packed) there will probably be an intervening unused byte.
Whether any performance or storage differences are significant will be heavily dependent on the application. Follow the usual rule of thumb - don't optimise until an issue is found.
However if you find semantic benefit in limiting the size then certainly do so - there is no general reason you shouldn't. The choice is similar to picking signed vs. unsigned integers, some programmers avoid unsigned types for values that will be ≥ 0 unless absolutely required for the extra range, while others appreciate the semantic benefit.
Summary: There is no right answer, its largely a subjective issue.
HTH
First of all: The memory footprint is close to completely meaningless. You are talking about 1 Byte vs. 4/8 Bytes. (If the memory alignment does not force the usage of 4/8 bytes whatever you chosed.) How many NS_ENUM (C) objects do you want to have in your running app?
I guess that the reason is pretty easy: NSInteger is akin of "catch all" integer type in Cocoa. That makes assignments easier, especially you do not have to care about assigning a bigger integer type to a smaller one. Without casting this would lead to warnings.
Having more than one integer type in a desktop app with a 32/64 bit model is akin of an anachronism. Nor a Mac neither a MacBook neither an iPhone is an embedded micro controller …
You can use any integer data type including uint8_t with NS_ENUM as.
typedef NS_ENUM(uint8_t, eEnumAddEditViewMode) {
eWBEnumAddMode,
eWBEnumEditMode
};
In old c style standard NSInteger is default, because NSInteger is akin of "catch all" integer type in objective c. and developer can easily type boxing and unboxing with their own variable. This is just developer friendly best practise.

Integer Precision and Conversion Errors

I have been programming Objective-C for only a few weeks. My experience in programming languages such as basic, visual basic, C++ and PHP is much more extensive starting back in 1987 and continuing forward to today. Although, for the last 5 years, I have exclusively coded PHP.
Today, I find myself confused by what I perceive to be bit conversion errors within the Objective-C language. I first noticed this the other day when trying to divide an integer (84) converted to a float by a float (10.0). This produced 8.399999, instead of the 8.400 I was hoping for. I coded a way around the issue and moved on.
Today, I am extracting an (int) 0 from an NSMutableDictionary. I store it first in an NSInteger and second in an int variable. The values should be 0 for both cases, but for both cases, I get the integer value 151229568. (See screenshot)
I remember from my early programming years that we had to worry about the size of the container, because pointing to block of memory with a 32-bit pointer to access a 4-bit value resulted in capturing all the data associated with other values and thus resulted in what appeared to be the wrong number being captured. With implicit memory management and type-conversions becoming the norm, I have not had to worry about this kind of issue for years, and now that I am confronted with it again, I need advice and clarification from programmers who are more familiar with this topic in todays programming environments.
Questions:
Is this a case of incorrect pointer sizing or something else?
What is happening on the back-end to produce this conversion from 0 to another number?
What can I do to get better precision and accuracy from my Objective-C calculations and variable assignments?
Code:
NSInteger hsibs = [keyData objectForKey:#"half_sibs"];
int hsibsi = [keyData objectForKey:#"half_sibs"];
//breakpoint and screen capture of variables in stack
I don't know Objective C all that well, but it looks like the method you use to obtain your data is returning a data type of id (see this reference), and not int
Looks like you either need to cast it or get the integer value in such a manner:
NSInteger hsibs = [[keyData objectForKey:#"half_sibs"] integerValue];
int hsibsi = [[keyData objectForKey:#"half_sibs"] intValue];
and then see if you get the expected results.

How are the digits in ObjC method type encoding calculated?

Is is a follow-up to my previous question:
What are the digits in an ObjC method type encoding string?
Say there is an encoding:
v24#0:4:8#12B16#20
How are those numbers calculated? B is a char so it should occupy just 1 byte (not 4 bytes). Does it have something to do with "alignment"? What is the size of void?
Is it correct to calculate the numbers as follows? Ask sizeof on every item and round up the result to multiple of 4? And the first number becomes the sum of all the other ones?
The numbers were used in the m68K days to denote stack layout. That is, you could literally decode the the method signature and, for just about all types, know exactly which bytes at what offset within the stack frame you could diddle to get/set arguments.
This worked because the m68K's ABI was entirely [IIRC -- been a long long time] stack based argument/return passing. There wasn't anything shoved into registers across call boundaries.
However, as Objective-C was ported to other platforms, always-on-the-stack was no longer the calling convention. Arguments and return values are often passed in registers.
Thus, those offsets are now useless. As well, the type encoding used by the compiler is no longer complete (because it never was terribly useful) and there will be types that won't be encoded. Not too mention that encoding some C++ templatized types yields method type encoding strings that can be many Kilobytes in size (I think the record I ran into was around 30K of type information).
So, no, it isn't correct to use sizeof() to generate the numbers because they are effectively meaningless to everything. The only reason why they still exist is for binary compatibility; there are bits of esoteric code here and there that still parse the type encoding string with the expectation that there will be random numbers sprinkled here and there.
Note that there are vestiges of API in the ObjC runtime that still lead one to believe that it might be possible to encode/decode stack frames on the fly. It really isn't as the C ABI doesn't guarantee that argument registers will be preserved across call boundaries in the face of optimization. You'd have to drop to assembly and things get ugly really really fast (>shudder<).
The full encoding string is constructed (in clang) by the method ASTContext::getObjCEncodingForMethodDecl, which you can find in lib/AST/ASTContext.cpp.
The method that does the size rounding is ASTContext::getObjCEncodingTypeSize, in the same file. It forces each size to be at least the size of an int. On all of Apple's current platforms, an int is 4 bytes.
The stack frame size and argument offsets are calculated by the compiler. I'm actually trying to track this down in the Clang source myself this week; it possibly has something to do with CodeGenTypes::arrangeObjCMessageSendSignature. (Looks like Rob just made my life a lot easier!)
The first number is the sum of the others, yes -- it's the total space occupied by the arguments. To get the size of the type represented by an ObjC type encoding in your code, you should use NSGetSizeAndAlignment().

What does the floating point "f" designator signify?

I wonder if someone can clarify what the "f" behind a floating point number is used to signify?
float myFloat = 12.0f;
as apposed to:
float myFloat = 12.0;
I have seen this used many times but its pretty hard to find an explanation either online or in books. I am assuming its either something carried over from another language thats supported for consistency by C or maybe its there as a directive for the compiler when it comes to evaluate the maths.
I am just curious if there is any practical difference between the "f" and using the "." to signify a floating point number?
It means it's a single-precision float rather than a double precision double.
From the C99 standard:
An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float.
Objective-C is based on C, maybe not C99, but this convention has been around in C for a long time.
There are sometimes performance concerns when converting from float to double, and you can avoid them by using the 'f'. Also when doing say a square root, sin,cos, etc, a wild guess would say that
float answer = sqrt(12.0f)
is about 10x slower than
float answer = sqrtf(12.0f)
It really makes a difference on the phone and iPad, if you are doing millions of these kinds of operations. Stay in float if you need speed and can deal with the lower resolution. If you are not good at math, or not using much math in your program use double everywhere, as there are more gotchas when using the lower precision 32 bit float.

How to correctly name a variable which represents a value of 1 - n?

It obviously depends on the context you are using them in but, I was wondering if there is a universally accepted way to name such variables, or at least in a mathematical context.
I've often seen:
float k = someValue;
float oneMinusK = 1 - k;
...which seems as descriptive as much as meaningless to me.
Please note that I'm not asking how to name a variable, but how to do it in this very case. Examples and contexts where you used them will be much appreciated,
Thanks.
In probability 1-k is the probability of X not occurring, given that k is the probability of X occurring.
So
float will_win_lottery = 0.00000000001;
float will_not_win_lottery = 1 - will_win_lottery;
You should name your variables based on what it means in terms of the domain you are working on not the algorithm you used to produce it. Thus if k represented your house number k-1 may represent your next door neighbors house number. Name it accordingly.
I would call it the Complement.
I would probably calculate that when I needed it. How much time do you think it saves to store it in a variable? Remember that premature optimization is the root of all evil.
There is no way to answer your question without knowing what "k" represents. Ironicly, the reason why that is not possible is the poor naming of the variable "k" in the first place, so that is what you should worry about instead. If you give "k" a more describing name, a good choise of naming for "k-1" should come naturally, like in the example of "will_win_lottery" and "will_not_win_lottery".
Your usage already seems descriptive enough, just go with it.
Are these supposed to be constants ?
If you are doing it for legibility reasons exclusively why not create a method a la Dan's suggestion.
float complement(float n) { return (1.0 - n); }
Does it really matter? Use i; it's not any less descriptive than k. Things like this need to be documented/commented if you're that OCD about code descriptiveness.