This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does the 'k' prefix indicate in Apple's APIs?
Objective C - Why do constants start with k
For example, the result codes defined for Audio Format Services:
kAudioFormatUnspecifiedError
kAudioFormatUnsupportedPropertyError
etc...
What does that leading k stand for? I've always assumed key, since such constants are often used as the keys in dictionaries, but those result codes are an example of where the constant is just a return value, not (as far as a client of the API can determine) a key.
I imagine that it merely stands for 'k'onstant, where 'k' is used because 'c' is already commonly used to indicate class or in Hungarian notation character.
The usage has historical precedent; early pocket calculators used 'k' to indicate constant mode (where repeated operation of = repeated the last operation) because 'c' was used for clear.
You can find the answer here.
Answer one
Constant names (#defines, enums, const local variables, etc.) should start with a
lower-case k and then use mixed case to delimit words, i.e.
kInvalidHandle, kWritePerm.
Though a pain to write, they are absolutely vital to keeping our code
readable. The following rules describe what you should comment and
where. But remember: while comments are very important, the best code
is self-documenting. Giving sensible names to types and variables is
much better than using obscure names and then trying to explain them
through comments.
But it has since been removed in the live version of the document. It
should be noted that it goes against the the Official Coding Guidelines
for Cocoa from Apple.
Cocoa coding guidelines
It was the coding standard left over when Apple used pascal. K was the prefix as opposed to all caps for other C languages.
Related
This question already has answers here:
"Backwards" Conditionals in C [duplicate]
(4 answers)
Closed 6 years ago.
Lately I've been noticing the style of some programmers who write "if" statements backwards. That is, in the test they put the constant value first and then the variable that they are testing second. So for example they write:
bar = foo();
if (MY_CONSTANT == bar) {
/* then do something */
}
To me, this makes code somewhat difficult to read. Since we are really talking about testing the value of the variable "bar" and not all variables that are equal to "MY_CONSTANT", I always put the variable first. Its sort of a unspoken grammar.
Anyhow, I see that some programmers ALWAYS do this in the opposite order. Further, I've only noticed this in the past few years. I've been programming in C for over 25 years and I've not seen this until, say, about the last 4 years or so. So my question is:
Is there a reason people are doing this and if so what is it? Is this a common standard in some languages, or projects, or is it taught in some universities? or is that just a few people trying to be different?
This is called "Yoda-Style" (or "Yoda conditions" or "Yoda notation") and should prevent you from accidentally writing
if (bar = MY_CONSTANT) {
/* then do something */
}
since
if (MY_CONSTANT = bar) {
/* then do something */
}
would trigger a compiler error.
The name is derived from the uncommon twisted sentence construction the Star Wars character Yoda is also using.
In my opinion using "Yoda-Style" makes understanding of code harder because it is against the normal sentence construction rules. Also code quality checker (or as mentioned in the comments maybe even the compiler itself) should complain about such assignments anyway, so that (imho) there is no good reason to obfuscate your code.
This is something of a best practice which someone thought best 15 years ago or so. Alleged benefit was that it would prevent someone from doing accidental assignments instead of comparison.
It was dubious back than, it is 100% moot nowadays since any compiler worth using will warn about assignment in branch operator, but hordes of lemmings still copy best practice without even thinking what it means or what it is for.
Is there any rationale for the abbreviated way standard C functions are written? For example, malloc() is short for 'memory allocation'. sprintf() is 'string print formatted'. Neither of these names are very good at telling you what the function actually does. It never occurred to me how terrible some of these abbreviated function names are until recently when I had to teach a new intern many of these functions.
When the language was being developed, was there any reason malloc() was chosen over memAllocate() or something similar? My best guess would be that they more closely resemble UNIX commands, but that doesn't feel like the right answer.
Check out http://publications.gbdirect.co.uk/c_book/chapter2/keywords_and_identifiers.html -
The problem is that there was never any guarantee that more than a
certain number of characters would be checked when names were compared
for equality—in Old C this was eight characters, in Standard C this
has changed to 31.
Basically, in the past (long while back) you could only count on the the first eight characters for uniqueness in a function name. So, you end up with a bunch of short names for the core functions.
As Neal Stephenson wrote about Unix in In the Beginning Was the Command Line,
Note the obsessive use of abbreviations and avoidance of capital letters; this is a system invented by people to whom repetitive stress disorder is what black lung is to miners. Long names get worn down to three-letter nubbins, like stones smoothed by a river.
The first version of Unix and the first C compiler were written using versions of ed. Not vi, not emacs, not anything resembling an IDE, but the line-based ed. There comes a point where reducing the number of keystrokes really does increase the number of SLOC you can write per day, when you're inventing something brand-new and writing it for the first time.
The historical justification is of course that historically the C standard only required implementations to distinguish the initial 6 characters of external identifier names. This allowance was removed in C99. However, users of the C language generally:
Aim to write source code in such a way that it fits in a reasonable number of columns, usually 80 or fewer, which is difficult with long identifier names.
Type identifier names with a keyboard, which is difficult and a waste of time when the identifiers are long.
Tend to prefer high information density and signal-to-noise ratio in source code.
This question already has an answer here:
Creating variable names from parameters
(1 answer)
Closed 8 years ago.
Is is possible for your code to generate new variables in c? For example, if I made "example_variable = 15", is there any way to automatically generate 15 new variables such as: "generated_variable_1", "generated_variable_2", "generated_variable_3", all the way to "generated_variable_15"?
I'm very new to c, and I haven't had a proper introduction to it, so I only know the basics, especially when it comes to variables. I am pretty sure this is really high-level stuff, so I'm sorry if the question doesn't make sense. I am open to any suggestions for alternate ways of generating the variables.
I know there are probably answers already out there, but I've had trouble finding them and would like answers specific to what I'm looking for, as opposed to piecing together what I need from what I can find.
What you are talking about - generating variables at runtime - is not possible in C. The reason is that C is a low-level language and does not expose an API for runtime manipulation. In fact, once compiled, C programs don't use variables - are values are stored directly in memory using memory addresses.
The closet equivalent to what you're looking for that's available in C is an "array". To declare an array, you can do:
int var[15];
int var2[n]; // in C99+, n is a variable saying how many elements you want in the array
You can also do this with malloc, but this is a bit more complicated and then you must free the values.
A running C program doesn't use your variable names at all. Those names were useful for the compiler to build the program, but are discarded before you run it. This means that in C (but not in interpreted languages like python):
If you rename your variables, you get the exact same program
If you do strings <your program> you won't see any variable names (unless you retained debugging symbols)
Hence, runtime is too late to create new variables. In C, variables are compile-time only. Of course, you can use arrays, or dictionaries, to simulate run-time variable creation, like the other answer, and a few commenters, suggest.
I have a C program that now I need to do support to UTF-8 characters. What must I know in order to perform that? I've always hear how problematic is handle it in a C/C++ environment. Why exactly is it problematic? How does it differ from an usual C character, also its size? Can I do it without any operating system help, in pure C and still make it portable? what else I should have asked but I didn't? what I'm looking for implement is it: The characters are a name with accents(like french word: résumé) that I need to read it and put into a symbol table and then search and print them from a file. It's part of my configuration file parsing(very much .ini-like)
There's an awesome article written by Joel Spolsky, one of the Stack Overflow creators.
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
Apart from that, you might want to query some other Q&A's regarding this subject, like Handling special characters in C (UTF-8 encoding).
As cited in the aforementioned Q&A, Tips on Using Unicode with C/C++ might give you the basics.
Two good links that i have used in the past:
The-Basics-of-UTF8
reading-unicode-utf-8-by-hand-in-c
valter
(in c90) (linux)
input:
sqrt(2 - sin(3*A/B)^2.5) + 0.5*(C*~(D) + 3.11 +B)
a
b /*there are values for a,b,c,d */
c
d
input:
cos(2 - asin(3*A/B)^2.5) +cos(0.5*(C*~(D)) + 3.11 +B)
a
b /*there are values for a,b,c,d */
c
d
input:
sqrt(2 - sin(3*A/B)^2.5)/(0.5*(C*~(D)) + sin(3.11) +ln(B))
/*max lenght of formula is 250 characters*/
a
b /*there are values for a,b,c,d */
c /*each variable with set of floating numbers*/
d
As you can see infix formula in the input depends on user.
My program will take a formula and n-tuples value.
Then it calculate the results for each value of a,b,c and d.
If you wonder I am saying ;outcome of program is graph.
/sometimes,I think i will take input and store in string.
then another idea is arise " I should store formula in the struct"
but ı don't know how I can construct
the code on the base of structure./
really, I don't know way how to store the formula in program code so that
I can do my job.
can you show me?
/* a,b,c,d is letters
cos,sin,sqrt,ln is function*/
You need to write a lexical analyzer to tokenize the input (break it into its component parts--operators, punctuators, identifiers, etc.). Inevitably, you'll end up with some sequence of tokens.
After that, there are a number of ways to evaluate the input. One of the easiest ways to do this is to convert the expression to postfix using the shunting yard algorithm (evaluation of a postfix expression is Easy with a capital E).
You should look up "abstract syntax trees" and "expression trees" as well as "lexical analysis", "syntax", "parse", and "compiler theory". Reading text input and getting meaning from it is quite difficult for most things (though we often try to make sure we have simple input).
The first step in generating a parser is to write down the grammar for your input language. In this case your input language is some Mathematical expressions, so you would do something like:
expr => <function_identifier> ( stmt )
( stmt )
<variable_identifier>
<numerical_constant>
stmt => expr <operator> stmt
(I haven't written a grammar like this {look up BNF and EBNF} in a few years so I've probably made some glaring errors that someone else will kindly point out)
This can get a lot more complicated depending on how you handle operator precedence (multiply and device before add and subtract type stuff), but the point of the grammar in this case is to help you to write a parser.
There are tools that will help you do this (yacc, bison, antlr, and others) but you can do it by hand as well. There are many many ways to go about doing this, but they all have one thing in common -- a stack. Processing a language such as this requires something called a push down automaton, which is just a fancy way of saying something that can make decisions based on new input, a current state, and the top item of the stack. The decisions that it can make include pushing, popping, changing state, and combining (turning 2+3 into 5 is a form of combining). Combining is usually referred to as a production because it produces a result.
Of the various common types of parsers you will almost certainly start out with a recursive decent parser. They are usually written directly in a general purpose programming language, such as C. This type of parser is made up of several (often many) functions that call each other, and they end up using the system stack as the push down automaton stack.
Another thing you will need to do is to write down the different types of words and operators that make up your language. These words and operators are called lexemes and represent the tokens of your language. I represented these tokens in the grammar <like_this>, except for the parenthesis which represented themselves.
You will most likely want to describe your lexemes with a set of regular expressions. You should be familiar with these if you use grep, sed, awk, or perl. They are a way of describing what is known as a regular language which can be processed by something known as a Finite State Automaton. That is just a fancy way of saying that it is a program that can make a decision about changing state by considering only its current state and the next input (the next character of input). For example part of your lexical description might be:
[A-Z] variable-identifier
sqrt function-identifier
log function-identifier
[0-9]+ unsigned-literal
+ operator
- operator
There are also tools which can generate code for this. lex which is one of these is highly integrated with the parser generating program yacc, but since you are trying to learn you can also write your own tokenizer/lexical analysis code in C.
After you have done all of this (it will probably take you quite a while) you will need to have your parser build a tree to represent the expressions and grammar of the input. In the simple case of expression evaluation (like writing a simple command line calculator program) you could have your parser evaluate the formula as it processed the input, but for your case, as I understand it, you will need to make a tree (or Reverse Polish representation, but trees are easier in my opinion).
Then after you have read the values for the variables you can traverse the tree and calculate an actual number.
Possibly the easiest thing to do is use an embedded language like Lua or Python, for both of which the interpreter is written in C. Unfortunately, if you go the Lua route you'll have to convert the binary operations to function calls, in which case it's likely easier to use Python. So I'll go down that path.
If you just want to output the result to the console this is really easy and you won't even have to delve too deep in Python embedding. Since, then you only have to write a single line program in Python to output the value.
Here is the Python code you could use:
exec "import math;A=<vala>;B=<valb>;C=<valc>;D=<vald>;print <formula>".replace("^", "**").replace("log","math.log").replace("ln", "math.log").replace("sin","math.sin").replace("sqrt", "math.sqrt").replace("cos","math.cos")
Note the replaces are done in Python, since I'm quite sure it's easier to do this in Python and not C. Also note, that if you want to use xor('^') you'll have to remove .replace("^","**") and use ** for powering.
I don't know enough C to be able to tell you how to generate this string in C, but after you have, you can use the following program to run it:
#include <Python.h>
int main(int argc, char* argv[])
{
char* progstr = "...";
Py_Initialize();
PyRun_SimpleString(progstr);
Py_Finalize();
return 0;
}
You can look up more information about embedding Python in C here: Python Extension and Embedding Documentation
If you need to use the result of the calculation in your program there are ways to read this value from Python, but you'll have to read up on them yourself.
Also, you should review your posts to SO and other posts regarding Binary Trees. Implement this using a tree structure. Traverse as infix to evaluate. There have been some excellent answers to tree questions.
If you need to store this (for persistance as in a file), I suggest XML. Parsing XML should make you really appreciate how easy your assignment is.
Check out this post:
http://blog.barvinograd.com/2011/03/online-function-grapher-formula-parser-part-2/
It uses ANTLR library for parsing math expression, this one specifically uses JavaScript output but ANTLR has many outputs such as Java, Ruby, C++, C# and you should be able to use the grammar in the post for any output language.