Can't use #define for convenience [closed] - ios

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I may have made some syntax mistakes, but I can't understand why my code isn't working:
In top of .m file I wrote:
#define kCountry "Country";
In this case I got red warning from xCode - expected ]
Then in function body:
floatCountries = 74,2;
[[NSUserDefaults standardUserDefaults]setFloat:floatCountries forKey:kCountry];
float test= [[NSUserDefaults standardUserDefaults]floatForKey:kCountry];
NSLog(#"%f", test);
In that one - expected expression.
That may sound a bit stupid, but I want to simplify my code and use this, please help me! :)

Remove the semi-colon from the end of the define and add the '#':
#define kCountry #"Country"

Use:
#define kCountry #"Country"
You added a semicolon at the end.
And as this will be replaced for string value, you need to put #

To explain why this didn't work:
The semicolon
#define kCountry "Country";
In this case i got red warning from xCode - expected ]
There's no such thing as a “red warning”. Warnings are yellow; errors are red.
(Unless you turn on “Treat Warnings as Errors”; then, in a sense, all the warnings are red—because then they're errors.)
Anyway.
Preprocessor directives such as #define do not require a semicolon. If you include one, it becomes part of the directive.
The preprocessor replaces any macro with whatever you defined it as. In this case, you defined a macro named “kCountry” with the value “"Country;”. Note that the semicolon is part of the value—the directive ends at the end of the line, not at a semicolon.
Thus, when you go to use the macro:
[[NSUserDefaults standardUserDefaults]setFloat:floatCountries forKey:kCountry];
float test= [[NSUserDefaults standardUserDefaults]floatForKey:kCountry];
The preprocessor replaces the macro as follows:
[[NSUserDefaults standardUserDefaults]setFloat:floatCountries forKey:"Country";];
float test= [[NSUserDefaults standardUserDefaults]floatForKey:"Country";];
A semicolon can't go inside a statement; it must come after. Thus, the above statements are invalid.
The fix is to remove the semicolon from the line where you #defined the macro, so that the semicolon does not appear in the output:
[[NSUserDefaults standardUserDefaults]setFloat:floatCountries forKey:"Country"];
float test= [[NSUserDefaults standardUserDefaults]floatForKey:"Country"];
By the way, Xcode has an option in its Jump Bar to show you the complete preprocessed version of the code, as the compiler will see it. That can be handy when investigating macro problems.
So, that's one of the problems. The other one was…
The kind of string you used
"Country" is a C string. It's only usable with the C string and stdio libraries (including the functions printf, strcat, etc.) and various other APIs that require C strings (such as +[NSString stringWithUTF8String:] and +[NSString stringWithCString:encoding:]).
NSUserDefaults, like everything else in Cocoa that requires a string, requires a Cocoa string object—an NSString. The syntax for an NSString literal is the same, but with an # in front of it: #"Country".
Hence the version that works:
#define kCountry #"Country"
Which produces the preprocessed output:
[[NSUserDefaults standardUserDefaults]setFloat:floatCountries forKey:#"Country"];
float test= [[NSUserDefaults standardUserDefaults]floatForKey:#"Country"];
With no syntax errors and the right kind of string in both places, this is the version that will work.
Oh, and, as Anoop Vaidya already pointed out:
The number syntax
You tried to assign a number to a variable, but I think you'll find a different number there than you were expecting.
floatCountries = 74,2;
If you print the value of this variable with a statement such as:
NSLog(#"%f", floatCountries);
You'll find that the output is 2.0.
C has an operator called the comma operator, and it is simply x, y, where x and y can be any expression (ideally of types that are compatible with each other—e.g., both numbers).
The comma operator evaluates first the left-side expression, then the right-side expression, and itself evaluates to the right-side expression.
74,2 evaluates first the expression 74, and then the expression 2, and then evaluates to 2. Thus, you assign 2 (an int, which is converted automatically as needed) to the variable.
It may seem kind of silly to use this with literal numbers, and it is. The comma operator exists to be used with expressions that have side effects, such as expressions involving the ++ and -- operators.
Use of the comma operator is generally discouraged, because the resulting code is unclear: as a rule, each line should do one thing, but a line such as x = ++y, --z; does three things.
Nonetheless, it is valid, as you found. You should get a warning, though, if you have the “unused value” warning turned on (as you should), because half of the expression is, in fact, unused—you drop the 74 on the floor. Harmless, but a symptom that this isn't what you meant to do.
What you want is:
floatCountries = 74.2;

Related

why we need both Look Ahead symbol and read ahead symbol in Compiler

well i was reading some common concepts regarding parsing in compiler..i came across look ahead and read ahead symbol i search and read about them but i am stuck like why we need both of them ? would be grateful for any kind suggestion
Lookahead symbol: when node being considered in parse tree is for a terminal, and the
terminal matches lookahead symbol,then we advance in both parse and
input
read aheadsymbol: lexical analyzer may need to read some character
before it can decide on the token to be returned
One of these is about parsing and refers to the next token to be produced by the lexical scanner. The other one, which is less formal, is about lexical analysis and refers to the next character in the input stream. It should be clear which is which.
Note that while most parsers only require a single lookahead token, it is not uncommon for lexical analysis to have to backtrack, which is equivalent to examining several unconsumed input characters.
I hope I got your question right.
Consider C.
It has several punctuators that begin the same way:
+, ++, +=
-, --, -=, ->
<, <=, <<, <<=
...
In order to figure out which one it is when you see the first + or - or <, you need to look ahead one character in the input (and then maybe one more for <<=).
A similar thing can happen at a higher level:
{
ident1 ident2;
ident3;
ident4:;
}
Here ident1, ident3 and ident4 can begin a declaration, an expression or a label. You can't tell which one immediately. You can consult your existing declarations to see if ident1 or ident3 is already known (as a type or variable/function/enumeration), but it's still ambiguous because a colon may follow and if it does, it's a label because it's permitted to use the same identifier for both a label and a type/variable/function/enumeration (those two name spaces do not intersect), e.g.:
{
typedef int ident1;
ident1 ident2; // same as int ident2
int ident3 = 0;
ident3; // unused expression of value 0
ident1:; // unused label
ident2:; // unused label
ident3:; // unused label
}
So, you may very well need to look ahead a character or a token (or "unread" one) to deal with situations like these.

How do you read the "<<" and ">>" symbols out loud?

I'm wondering if there is a standard way, if we are pronouncing typographical symbols out loud, for reading the << and >> symbols? This comes up for me when teaching first-time C++ students and discussing/fixing exactly what symbols need to be written in particular places.
The best answer should not be names such as "bitwise shift" or "insertion", because those refer to more specific C++ operators, as opposed to the context-free symbol itself (which is what we want here). In that sense, this question is not the same as questions such as this or this, none of whose answers satisfy this question.
Some comparative examples:
We can read #include <iostream> as "pound include bracket iostream
bracket".
We can read int a, b, c; as "int a comma b comma c
semicolon".
We can read if (a && b) c = 0; as "if open parenthesis a double ampersand b close parenthesis c equals zero semicolon".
So an equivalent question would be: How do we similarly read cout << "Hello";? At the current time in class we are referring to these symbols as "left arrow" and "right arrow", but if there is a more conventional phrasing I would prefer to use that.
Other equivalent ways of stating this question:
How do we typographically read <<?
What is the general name of the symbol <<, whether being used for bit-shifts, insertion, or overloaded for something entirely new?
If a student said, "Professor, I don't remember how to make an insertion operator; please tell me what symbol to type", then what is the best verbal response?
What is the best way to fill in this analogy? "For the multiplication operation we use an asterisk; for the division operation we use a forward-slash; for the insertion operation we use ____."
Saw this question through your comment on Slashdot. I suggest a simpler name for students that uses an already common understanding of the symbol. In the same way that + is called "plus" and - is (often) called "minus," you can call < by the name "less" or "less-than" and > by "greater" or "greater-than." This recalls math operations and symbols that are taught very early for most students and should be easy for them to remember. Plus, you can use the same name when discussing the comparison operators. So, you would read
std::cout << "Hello, world!" << std::endl;
as
S T D colon colon C out less less double-quote Hello comma world exclamation-point double-quote less less S T D colon colon end L semicolon.
Also,
#include <iostream>
as
pound include less I O stream greater
So, the answer to
"Professor, I don't remember how to make an insertion operator; please tell me what symbol to type."
is "Less less."
The more customary name "left/right angle bracket" should be taught at the same time to teach the more common name, but "less/greater" is a good reminder of what the actual symbol is, I think.
Chevron is also a neat name, but a bit obscure in my opinion, not to mention the corporate affiliation.
A proposal: Taking the appearance of the insertion/extraction operators as similar to the Guillemet symbols, we might look to the Unicode description of those symbols. There they are described as "Left-pointing double angle quotation mark" and "Right-pointing double angle quotation mark" (link).
So perhaps we could be calling the symbols "double-left angle" and "double-right angle".
My comment was mistaken (Chrome's PDF Reader has a buggy "Find in File" feature that didn't give me all of the results at first).
Regarding the OP's specific question about the name of the operator, regardless of context - then there is no answer, because the ISO C++ specification does not name the operators outside of a use context (e.g. the + operator is named "addition" but only with number types, it is not named as such when called to perform string concatenation, for example). That is, the ISO C++ standard does not give operator tokens a specific name.
The section on Shift Operators (5.8) only defines and names them for integral/enum types, and the section on Overloaded Operators does not confer upon them a name.
Myself, if I were teaching C++ and explaining the <</>> operators I would say "the double-angle-bracket operator is used to denote bitshifts with integer types, and insertion/extraction with streams and strings". Or if I were being terse I'd overload the word and simply say "the bitshift operator is overloaded for streams to mean something completely different".
Regarding the secondary question (in the comment thread) about the name of the <</>> operators in the context of streams and strings, the the C++14 ISO specification (final working-draft: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf ) does refer to them as "extractors and inserters":
21.4.8.9 Inserters and extractors
template<class charT, class traits, class Allocator>
basic_istream<charT,traits>&
operator>>(
basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str
);
(and the rest of the >> operator overload definitions follow)
This is further expanded upon on 2.7.2.2.2:
27.7.2.2.2 Arithmetic extractors
operator>>(unsigned short& val);
operator>>(unsigned int& val);
operator>>(long& val);
(and so on...)
cout << "string" << endl;// I really just say "send string to see out. Add end line."
i++; // i plus plus
auto x = class.func() // auto x equal class dot func
10 - ( i %4) * x; // ten minus the quantity i mod four times x
stdout // stud-out
stderr // stud-err
argc // arg see
argv // arg vee
char* // char pointer
&f // address of f
Just because it's an "extraction" or an "insertion" operator does not mean that is the OPERATION.
The operation is "input" and "output"
They are stream operators.
The natural label would be c-out stream output double-quote Hello world exclamation double-quote stream output endline
This the OPERATION you are doing (the verb)
What the ARM calls the operator is irrelevant in that it is a systemic way of looking at things and we are trying to help humans understand things instead

Lua pattern help (Double parentheses)

I have been coding a program in Lua that automatically formats IRC logs from a roleplay. In the roleplay logs there is a specific guideline for "Out of character" conversation, which we use double parentheses for. For example: ((<Things unrelated to roleplay go here>)). I have been trying to have my program remove text between double brackets (and including both brackets). The code is:
ofile = io.open("Output.txt", "w")
rfile = io.open("Input.txt", "r")
p = rfile:read("*all")
w = string.gsub(p, "%(%(.*?%)%)", "")
ofile:write(w)
The pattern here is > "%(%(.*?%)%)" I've tried multiple variations of the pattern. All resulted in fruitless results:
1. %(%(.*?%)%) --Wouldn't do anything.
2. %(%(.*%)%) --Would remove *everything* after the first OOC message.
Then, my friend told me that prepending the brackets with percentages wouldn't work, and that I had to use backslashes to 'escape' the parentheses.
3. \(\(.*\)\) --resulted in the output file being completely empty.
4. (\(\(.*\)\)) --Same result as above.
5. (\(\(.*?\)\) --would for some reason, remove large parts of the text for no apparent reason.
6. \(\(.*?\)\) --would just remove all the text except for the last line.
The short, absolute question:
What pattern would I need to use to remove all text between double parentheses, and remove the double parentheses themselves too?
You're friend is thinking of regular expressions. Lua patterns are similar, but different. % is the correct escape character.
Your pattern should be %(%(.-%)%). The - is similar to * in that it matches any number of the preceding sequence, but while * tries to match as many characters as it can (it's greedy), - matches the least amount of characters possible (it's non-greedy). It won't go overboard and match extra double-close-parenthesis.

?: in Objective-C [duplicate]

This question already has answers here:
Is this ternary conditional ?: correct (Objective) C syntax?
(4 answers)
Closed 8 years ago.
In this iOS tutorial, there is a line of code with a ? followed by a :. In the context of the comment for the code, I thought it was some sort of ternary operation, however, that's obviously not the syntax for a ternary operator. Is there a name for what is happening in this code with the ?:?
// Initialize the list of weather items if it doesn't exist
NSMutableArray *array = self.xmlWeather[#"weather"] ?: [NSMutableArray array];
It's a GCC extension:
6.7 Conditionals with Omitted Operands
The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.
Therefore, the expression
x ? : y
has the value of x if that is nonzero; otherwise, the value of y.
This example is perfectly equivalent to
x ? x : y
In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.

Hex constant = malformed number?

I have a Lua script, where I'm trying to use hex numbers (0x..). If I run this script in the console, with the official Windows binaries, it works fine. But if I run it in my application (simple dofile), I get
malformed number near '0x1F'
It doesn't matter what the hex is, I always get that error, as if it wouldn't support them. The library I'm using is Lua 5.1.4, and I've tried 2 different ones (the first one being one I've compiled myself), so that shouldn't be the problem.
Does anyone have a clue what might be wrong here?
Edit:
It's not the script. No matter what I do, a simple "foo = 0xf" already triggers the error, even if there's nothing else in the file.
Update:
tonumber("0xf")
This returns nil, while
tonumber("15")
work fine. There's definitely something wrong with hex in my libs...
If hex literals aren't working for you (though they should), you can always use hex from lua by doing tonumber("fe",16)
Why do functions have to be different in different compilers, ...why?
Alright, the problem was that Lua tries to convert numbers into double by default. For this it uses the function "strtod", which takes 2 arguments, the string, and a char pointer. The char pointer is supposed to point to the last position after the parsed number. Which for a hex number would mean the 'x', after the '0'. If this isn't the case, Lua assumes an error, and gives us this nice little error message.
I've compiled Lua using DMC, because I need the lib to be in OMF, and I assume others used DMC as well. But apparently DMC's strtod works differenty, since the pointers always point to the start of the string if it's a hex... or rather any invalid number.
I've now added a little hack, which checks for the x, if conversion to double failed. Not pretty, but it works fine for now.
int luaO_str2d (const char *s, lua_Number *result) {
char *endptr;
*result = lua_str2number(s, &endptr);
/* Hack for DMC */
if (endptr == s)
if(*(s+1) == 'x' || *(s+1) == 'X')
endptr++;
else
return 0; /* conversion failed */
I faced this bug with lua5.2. Lua 5.1 works fine.

Resources