objective-c equivalent to c++ numeric_limits::max() - objective-c

I've gotten used to utilizing the numeric_limits part of the C++ STL for initializing numeric types (int,float, etc.) to their largest possible value.
I.e. int i=numeric_limits::max()
Is there an equivalent to this in objective-c? I've seen using INT_MAX and FLT_MAX in google searches, but it seems like there should be a better way.

There is:
NSIntegerMax, NSIntegerMin, CGFLOAT_MAX etc.
These are sufficient for getting the numeric limits.

Related

GMP Library: How to check first m-bit of a big integer

I'm using gmp (big integer library)
I have a value b I need to check whether first m-bit of it, is zero.
I know if I convert b to string I can do checking, but it's not efficient.
Question 1: I need to know whether the library has a function that returns first m-bit of a big integer.
To encode a big integer c, I convert it to string and then concatenate it with m zeros, e.g. imagine c in binary is 11, then I encode as: 1100000000
Question 2: I need to know whether I can do encoding faster using the library's function
The GMP library provides plenty of bit manipulation primitives. Have a look at the Logical and Bit Manipulation Functions chapter from the documentation.
For your first question, I think you want to use mpz_tstbit. For your second question, it sounds like you're trying to perform some bit shifting, which can be done via the mpz_mul_2exp and the mpz_*_*_2exp functions.

Why does neither C nor Objective-C have a format specifier for Boolean values?

The app I'm working on has a credit response object with a Boolean "approved" field. I'm trying to log out this value in Objective C, but since there is no format specifier for Booleans, I have to resort to the following:
NSLog("%s", [response approved] ? #"TRUE" : #"FALSE");
While it's not possible, I would prefer to do something like the following:
NSLog("%b", [response approved]);
...where "%b" is the format specifier for a boolean value.
After doing some research, it seems the unanimous consensus is that neither C nor Objective-C has the equivalent of a "%b" specifier, and most devs end up rolling their own (something like option #1 above).
Obviously Dennis Ritchie & Co. knew what they were doing when they wrote C, and I doubt this missing format specifier was an accident. I'm curious to know the rationale behind this decision, so I can explain it to my team (who are also curious).
EDIT:
Some answers below have suggested it might be a localization issue, i.e. "TRUE" and "FALSE" are too English-specific. But wouldn't this be a dilemma that all languages face? i.e. not just C and Objective-C? Java and Ruby, among others, are able to implement "True" and "False" boolean values. Not sure why the authors of these langs didn't similarly punt on this choice.
In addition, if localization were the problem, I would expect it to affect other facets of the language as well. Take protected keywords, for instance. C uses English keywords like "include", "define", "return", "void", etc., and these keywords are arguably more difficult for non-English speakers to parse than keywords like "true" or "false".
Pure C (back to the K&R variety) doesn't actually have a boolean type, which is the fundamental reason why native printf and cousins don't have a native boolean format specifier. Expressions can evaluate to zero or nonzero integral values, which is what is interpreted in if statements as false or true, respectively in C. (Understanding this is the key to understand the semantics of the delightful !! "bang bang operator" syntax.)
(C99 did add a _Bool type, though unless you're using purest C you're unlikely to need it; derived languages and common platforms already have common boolean types or typedefs.)
The BOOL type is an ObjC construct, and -[NSString stringWithFormat:] (and NSLog) simply doesn't have an additional format specifier that does anything special with it. It certainly could (in addition to %#), and choose some reasonable string to drop in there; I don't know whether such a thing was ever considered, but it strikes me anyway as different in kind from all other format specifiers. How would you know to appropriately localize or capitalize the string representations of "yes" or "no" (or "true" or "false"?) etc? No other format specifier results in the library making decisions like that; all others are precisely numeric or insert the string result of another method call. It seems onerous, but making you choose what text you actually want in there is probably the most elegant solution.
What should the formatter display? 0 & 1? TRUE & FALSE? YES & NO? -1 and 1? What about other languages?
There's no good consistently right answer so they punted it to the app developer, for whom it'll be a clearer (and still simple) choice.
In C early days, there was no numeric printf() specifier for char, short either as there was little need for it. Now there is "%hhd" and "%hd". Any type narrower than int/unsigned was promoted.
Today, in C, _Bool type maybe printed with "%d".
#include <stdio.h>
int main(void) {
_Bool some_bool = 2;
printf("%d\n", some_bool); // prints 1 (or 0 when false)
return 0;
}
The missing link in C is its lack of a format specifier to scan into a _Bool. This leads to various solutions like the following which are not satisfactory with input like "T" or "false".
_Bool some_bool;
int temp;
scanf("%d", &temp);
some_bool = temp;

Converting std::int to System::Single

Apologies if there's an answer out there already; but all I seem to be getting is a bunch of "I want to turn my 1 into a 1.0" chaff from my Google searches.
First things first. No, I'm not talking about a simple Convert::ToSingle() call. Rather, I need to convert the representation of the data to a System::Single.
So in other words, I'd like to take int myInt = 1065353216;, and the result should be something like 1.000. I know the pure c++ method would be something like float myFloat=*(float *)&myInt;;but I need the managed version.
Thanks in advance for your help.
If you're in C++/CLI, you can do it the same way as you do in C++: float myFloat=*(float*)&myInt;
In pure managed-land, there are built-in methods to do this for double & Int64 (DoubleToInt64Bits and Int64BitsToDouble, but not for single & Int32. However, if you look at the implementation of those methods (MS Reference Source), you'll see that they're doing the exact same thing as you have listed, so that's also the managed way to do it. The only difference is if you do it in C#, you have to tag the method as unsafe.

Handling expressions in GMP

I introduced myself to the GMP library for high precision arithmetic recently. It seems easy enough to use but in my first program I am running into practical problems. How are expressions to be evaluated. For instance, if I have "1+8*z^2" and z is a mpz_t "large integer" variable, how am I to quickly evaluate this? (I have larger expressions in the program that I am writing.) Currently, I am doing every single operation manually and storing the results in temporary variables like this for the "1+8*z^2" expression:
1) first do mpt_mul(z,z,z) to square z
2) then define an mpz_t variable called "eight" with the value 8.
3) multiply the result from step one by this 8 and store in temp variable.
4) define mpz_t variable called "one" with value 1.
5) add this to the result in step 3 to find final answer.
Is this what I am supposed to be doing? Or is there a better way? It would really help if there was a user's manual for GMP to get people started but there's only the reference manual.
GMP comes with a C++ class interface which provides a more straightforward way of expressing arithmetic expressions. This interface uses C++ operator overloading to allow you to write:
mpz_class z;
1 + 8 * z**2
This is, of course, assuming you're using C++. If you are using C only, you may need to use the C interface to GMP which does not provide operator overloading.
Turns out that there's an unsupported expression parser distributed with GMP in a "expr" subdirectory. It's not part of GMP proper and is subject to change but it is discussed in a README file in that directory. It isn't guaranteed to do the calculation in the fastest way possible, so buyer beware.
So the user must manually evaluate all expressions when using GMP unless they wish to use this library or make their own expression parser.

Good Examples of Hungarian Notation? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
This question is to seek out good examples of Hungarian Notation, so we can bring together a collection of these.
Edit: I agree that Hungarian for types isn't that necessary, I'm hoping for more specific examples where it increases readability and maintainability, like Joel gives in his article (as per my answer).
The problem with asking for good examples of Hungarian Notation is that everyone's going to have their own idea of what a good example looks like. My personal opinion is that the best Hungarian Notation is no Hungarian Notation. The notation was originally meant to denote the intended usage of a variable rather than its type but it's usually used for type information, particularly for Form controls (e.g., txtFirstName for a text box for someone's first name.). This makes the code less maintainable, in terms of readability (e.g., "prepIn nounTerms prepOf nounReadability") and refactoring for when the type needs to be changed (there are "lParams" in the Win32 API that have changed type).
You should probably consider not using it at all. Examples:
strFirstName - this can just be firstName since it's obvious what it's for, the type isn't that important and should be obvious in this case. If not obvious, the IDE can help you with that.
txtFirstName - this can change to FirstNameTextBox or FirstName_TextBox. It reads better and you know it's a control and not just the text.
CAccount - C was used for class names in MFC but you really don't need it. Account is good enough. The uppercase name is the standard convention for types (and they only appear in specific places so they won't get confused with properties or methods)
ixArray (index to array) - ix is a bit obscure. Try arrayIndex.
usState (unsafe string for State) - looks like "U.S. State". Better go with state_UnsafeString or something. Maybe even wrap it in an UnsafeString class to at least make it type-safe.
The now classic article, as mentioned in other Hungarian posts, is the one from Joel's site:
http://www.joelonsoftware.com/articles/Wrong.html
p
(for pointer). Its pretty much the only prefix I use. I think it adds a lot to a variable (eg that its a pointer) and so should be treated a little more respectfully.
Hungarian for datatypes is somewhat passe now IDEs can tell you what the type is (in only a few seconds hovering over the variable name), so its not so important. But treating a pointer as if its data is not good, so you want to make sure it's obvious to the user what it is even if he makes assumptions he shouldn't when coding.
t
Tainted data. Prefix all data incoming from an untrusted source to make that variable as tainted. All tainted data should be cleansed before any real work is done on it.
It's pointless to use Hungarian to indicate types because the compiler already does it for you.
Where Hungarian is useful is to distinguish between logically different sorts of variables that have the same raw type. For example, if you are using ints to represent coordinates, you could prefix x coordinates with x, y coordinates with y and distances with d. So you would have code that looks like
dxHighlight = xStart - xEnd
yHighlight = yLocation + 3
yEnd = yStart + dyHeight
dyCode = dyField * 2
and so on. It's useful because you can spot errors at a glance: If you add a dy to a y, you always get a y. If you subtract two x's you always get a dx. If you multiply a dy by a scalar, you always get a dy. And so on. If you see a line like
yTop = dyText + xButton
you know at a glance that it is wrong because adding a dy and a x does not make sense. The compiler could not catch this for you because as far as it can tell, you are adding an int to an int which is fine.
Do not use language specific prefixes.
We use:
n: Number
p: Percentage 1=100% (for interest rates etc)
c: Currency
s: String
d: date
e: enumeration
o: object (Customer oCustomer=new Customer();)
...
We use the same system for all languages:
SQL
C
C#
Javascript
VB6
VB.net
...
It is a life saver.
Devil's Advocate: The best example of Hungarian notation is not to use it. :D
We do not gain any advantage to using Hungarian notation with modern IDEs because they know the type. It adds work when refactoring a type for a variable since the name would also have to be changed (and most of the time when you are dealing with a variable you know what type it is anyway).
You can also get into ordering issues with the notation. If you use p for pointer and a for address do you call your variable apStreet or paStreet? Readability is diminished when you don't have consistency, and you have to use up valuable mind space when you have to remember the order that you have to write the notation in.
I find hungarian notation can sometimes be useful in dynamic languages. I'm specifically thinking of Server Side Actionscript (essentially just javascript), but it could apply elsewhere. Since there's no real type information at all, hungarian notation can sometimes help make things a bit easier to understand.
Hungarian notation (camel casing, as I learned it) is invaluable when you're inheriting a software project.
Yes, you can 'hover' over a variable with your IDE and find out what class it is, but if you're paging through several thousand lines of code you don't want to have to stop for those few seconds - every.... single.... time....
Remember - you're not writing code for you or your team alone. You're also writing it for the person who has to pick up this code 2-5 years down the road and enhance it.
I was strongly against Hungarian notation until I really started reading about it and trying to understand it's original intent.
After reading Joels post "Wrong" and the article "Rediscovering Hungarian Notation" I really changed my mind. Done correct I belive it must be extremly powerful.
Wrong by Joel Spolsky
http://www.joelonsoftware.com/articles/Wrong.html
Rediscovering Hungarian Notation
http://codingthriller.blogspot.com/2007/11/rediscovering-hungarian-notation.html
I belive that most Naysayers have never tried it for real and do not truly understand it.
I would love to try it out in a real project.
I think the key thing to take away from Joel's article, linked above, and Hungarian Notation in general, is to use it when there's something non-obvious about the variable.
One example, from the article, is encoded vs non encoded strings, it's not that you should use hungarian 'us' for unsafe strings and 's' for safe strings, it's that you should have some identifier to indicate that a string is either safe or not. If it becomes standard, it becomes easy to see when the standard is being broken.
The only Hungarian that's really useful anymore is m_ for member variables. (I also use sm_ for static members, because that's the "other" scope that still exists.) With widescreen monitors and compilers that take eight-billion-character-long variable names, abbreviating type names just isn't worth it.
m
When using an ORM (such as hibernate) you tend to deal managed and unmanaged objects. Changing an managed object will be reflected in the database without calling an explicit save, while dealing with a managaged object requires an explicit save call. How you deal with the object will be different depending on which it is.
I find that the only helpful point is when declaring interface controls, txtUsername, txtPassword, ddlBirthMonth. It isn't perfect, but it helps on large forms/projects.
I don't use it for variables or other items, just controls.
In addition to using 'p' for pointer, I like the idea of using 'cb' and 'cch' to indicate whether a buffer size parameter (or variable) is a count of bytes or a character count (I've also seen - rarely - 'ce' used to indicate a count of elements). So instead of conveying type, the prefix conveys use or intent.
I admit, I don't use the prefix as consistently as I probably should, but I like the idea.
A very old question, but here's a couple of "Hungarian" prefixes I use regularly:
my
for local variables, to distinguish locality where the name might make sense in a global context. If you see myFoo, it's only used in this function, regardless of anything else we do with Foos anywhere else.
myStart = GetTime();
doComplicatedOperations();
print (GetTime() - myStart);
and
tmp
for temporary copies of values in loops or multi-step operations. If you see two tmpFoo variables more than a couple of lines from each other, they're almost certainly unrelated.
tmpX = X;
tmpY = Y;
X = someCalc(tmpX, tmpY);
Y = otherCalc(tmpX, tmpY);
and sometimes old and new in for similar reasons to tmp, usually in longer loops or functions.
Well, I use it only with window control variables. I use btn_, txt_, lbl_ etc to spot them. I also find it helpful to look up the control's name by typing its type (btn_ etc).
I only ever use p for a pointer, and that's it. And that's only if I'm in C++. In C# I don't use any hungarian notation.
e.g.
MyClass myClass;
MyClass* pMyClass;
That's all :)
Edit: Oh, I just realised that's a lie. I use "m_" for member variables too. e.g.
class
{
private:
bool m_myVar;
}
I agree that Hungarian notation is no longer particularly useful. I thought that its original intention was to indicate not datatype, but rather entity type. In a code section involving the names of customers, employees and the user, for example, you could name local string variables cusName, empName and usrName. That would help distinguish among similar-sounding variable names. The same prefixes for the entities would be used throughout the application. However, when OO is used, and you're dealing with objects, those prefixes are redundant in Customer.Name, Employee.Name and User.Name.
The name of the variable should describe what it is. Good variable naming makes Hungarian notation useless.
However, sometimes you'd use Hungarian notation in addition to good variable naming. m_numObjects has two "prefixes:" m_ and num. m_ indicates the scope: it's a data member tied to this. num indicates what the value is.
I don't feel hindered at all when I read "good" code, even if it does contain some "Hungarian." Right: I read code, I don't click it. (In fact, I hardly use my mouse ever when coding, or any voodoo programming-specific lookup features.)
I am slowed when I read things like m_ubScale (yes, I'm looking at you, Liran!), as I have to look at its usage (no comments!) to find out what it scales (if at all?) and it's datatype (which happens to be a fixed-point char). A better name would be m_scaleFactor or m_zoomFactor, with a comment as a fixed-point number, or even a typedef. (In fact, a typedef would be useful, as there are several other members of several classes which use the same fixed-point format. However, some don't, but are still labeled m_ubWhatever! Confusing, to say the least.)
I think Hungarian was meant to be an additive to the variable name, not a replacement for information. Also, many times Hungarian notation adds nothing at all to the variable's readability, wasting bytes and read time.
Just my 2ยข.
There's no such thing as a good example of hungarian notation. Just don't use it. Not even if you are using a weakly typed language. You'll live happier.
But if you really need some reason not to use it, this is my favourite one, extracted from this great link:
One followon trick in the Hungarian notation is "change the type of a variable but leave the variable name unchanged". This is almost invariably done in windows apps with the migration from Win16 :- WndProc(HWND hW, WORD wMsg, WORD wParam, LONG lParam) to Win32 WndProc(HWND hW, UINT wMsg, WPARAM wParam, LPARAM lParam) where the w values hint that they are words, but they really refer to longs. The real value of this approach comes clear with the Win64 migration, when the parameters will be 64 bits wide, but the old "w" and "l" prefixes will remain forever.
I find myself using 'w' meaning 'working', as a prefix instead of 'temp' or 'tmp', for local variables that are just there to jockey data around, like:
Public Function ArrayFromDJRange(rangename As Range, slots As Integer) As Variant
' this function copies a Disjoint Range of specified size into a Variant Array 7/8/09 ljr
Dim j As Integer
Dim wArray As Variant
Dim rCell As Range
wArray = rangename.Value ' to initialize the working Array
ReDim wArray(0, slots - 1) ' set to size of range
j = 0
For Each rCell In rangename
wArray(0, j) = rCell.Value
j = j + 1
Next rCell
ArrayFromDJRange = wArray
End Function