Coding style of "if" statements [duplicate] - c

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.

Related

What does an "extra" semicolon means? [duplicate]

This question already has answers here:
Two semicolons inside a for-loop parentheses
(4 answers)
Endless loop in C/C++ [closed]
(12 answers)
Closed 4 years ago.
I was searching for an explanation for the "double semicolon" in the code:
for(;;){}
Original question.
I do not have enough reputation to even leave a comment so I need to create a new question.
My question is,
What does an "extra" semicolon means. Is this "double semicolon" or "extra semicolon" used for "something else"?
The question comes from a person with no knowledge of programing, just powered on my first arduino kit and feel like a child when LED blinked.
But it is the reality that the questions, like general occurence, are radiating the actual knowledge of the person asking the question.
And beyond "personal preference" in using while(1) or for(;;) is it helpful in using for(;;) where you do not have enough room for the code itself?
I have updated the question.
Thank you for the quick explanation. You opened my eyes with the idea of not using anything in for loop = ). From basic high school knowledge I am aware of for loop so thank you for that.
So for(;;) returns TRUE "by default"?
And my last line about the size of the code?
Or it is compiled and using for or while actually does not affect the compiled code size?
A for loop is often written
int i;
for (i = 0; i < 6; i++) {
...
}
Before the first semicolon, there is code that is run once, before the loop starts. By omitting this, you just have nothing happen before the loop starts.
Between the semicolons, there is the condition that is checked after every loop, and the for loop end if this evaluates to false. By omitting this, you have no check, and it always continues.
After the second semicolon is code that is run after every cycle, before that condition is evaluated. Omitting this just runs additional code at that time.
The semicolons are always there, there is nothing special about the face that they are adjacent. You could replace that with
for ( ; ; )
and have the same effect.
While for (;;) itself does not return true (It doesn't return anything), the second field in the parentheses of the for always causes the loop to continue if it is empty. There's no reason for this other than that someone thought it would be convenient. See https://stackoverflow.com/a/13147054/5567382. It states that an empty condition is always replaced by a non-zero constant, which is the case where the loop continues.
As for size and efficiency, it may vary depending on the compiler, but I don't see any reason that one would be more efficient than the other, though it's really up to the compiler. It could be that a compiler would allow the program to evaluate as non-zero a constant in the condition of a while loop, but recognise an empty for loop condition and skip comparison, though I would expect the compiler to optimize the while loop better. (A long way of saying that I don't know, but it depends on a lot.)

generating new variables in c [duplicate]

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.

What does `rc` for function return values mean? [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 10 years ago.
When reading C code, I often come across statements such as:
int rc = foo(bar, baz);
assert(rc != NULL);
where the variable rc is used for checking the return value of the function. I assume it's a mnemonic of some sort but can't deduce its meaning.
I would like to know its meaning to help with my understanding of the code.
I think it's "return code". Mostly used to refer to integer return codes of 0/NULL or 1 form.
rc stands for "rutabaga casserole". What? You don't think so?!
Well the fact is no one can say what this really stands for because there are no mandated names in C code. It could stand for "return code" or "remote control" or whatever the author had in his head at the time.
I would like to know it's meaning to help with my understanding of the code
Your argument is inherently flawed. If you want to understand code better, make sure you read the documentation and source of the functions being used, never trust that the names of functions, or data types yield any precedence into what the code is actually doing.
Edit to address the comment:
Actually, I think your argument is flawed, Mike. It is absurd to say that knowing commonly used variable names won't help you understand code, despite the fact that they are not mandated. For example, it is well known that i is commonly used (but not mandated) as a loop increment variable across all languages.
It's a fair argument to say that there are indeed variable names that people tend to follow. We'll see ret or rc for a return value or a return code, frequently we'll see single variables a,b,c,...,i,j,k, used for looping operators. However making an assumption about what a variable does based on a name is a terrible idea. Not only might your assumption about what the variable stands for be wrong (for example a simple i in an Ohm's law function might very well be the name chosen to represent current, nothing to do with looping) but also what makes sense to you might not be what made sense to the author.
example, the author has a variable int return_code. You might assume that's going to house the return code of the function, but maybe it's being used to check the returned value of a function called within the function you're evaluating and the variable int r is used for the return code instead.
Let's say you see the variable count is that going to be a loop iterator, or a count of a number of files, or is it a counting semaphore?
So, Chris Redford, I must respectfully disagree. It's not absurd to say that knowing commonly used variable names won't help understand code, because it won't do any better than reading the code itself, and it might lead you down a stray path thinking you know what is going on when you really don't.If you understand source code you'll see return xxx; or for(int yyy=0; and you won't have to make assumptions about what those variables are doing, you'll know for sure, and that's the only way to be guaranteed you know what's happening.
It often means "return code" or "result code", although it could basically mean anything depending on what the author intended. As naming conventions go, it's not that great. I mean, it's better than myVariable, but not by a whole lot.
I subscribe to the idea that variable names should be meaningful, and rc isn't terribly meaningful. If it means "result code", then my question is "result of what?" What does the return code designate?
I would guess "result code", but it's just a guess of course.

What does the "k" stand for in Cocoa constant names [duplicate]

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.

return from 1 point in function [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Should a function have only one return statement?
Hello,
gcc 4.4.4 c89
Is it good programming practice to return from 1 point in a function.
I have written a function below. However, I am returning from 2 possible points.
Is this good style?
static int init_data(struct timeout_data_t *timeout_data)
{
if(timeout_data == NULL) {
fprintf(stderr, " [ %s ] [ %d ]\n",
__func__, __LINE__);
return FALSE;
}
/* Assign data */
timeout_data->seconds = 3;
timeout_data->func_ptr = timeout_cb;
return TRUE;
}
If it aids readability, then there is nothing wrong with it.
Personally, I write this kind of code all of the time.
This is an ongoing religious-style debate without an accepted answer. There are many people on both sides of the argument, who feel strongly about it.
I don't think there's anything wrong with it personally, but the best approach is to go with the style guidelines of your team, if they have some (and if not, just ask about it. If anyone recoils in horror, it would be kinder to stick to single-return-point).
I've had managers that lived and died by the 1 return policy for the sake of "readability", even though it's much more readable in some cases without it.
The bottom line is... if the man that signs your paycheck says you're only going to use 1 return, use 1 return. The best way to do this is
type myfunc(params) {
type result = defaultValue;
// actual function here, word for word
// replace "return $1" with "result = $1"
return result;
}
This is a valid way to do things in their book, and will smile at your 1 return policy adherence. Of course, you know using this adds ZERO readability because all you've done is replace "return" (which is syntax highlighted) with "result =" which is not. But you've made your boss happy, which when you break it all down is what development is about anyway, right? :-)
In straight C, I think that error checking/parameter verification at the top of the function with a return (or possibly even multiple return points in the parameter verification) results in reasonably clean code. After that point, though, my opinion is that it is a good idea to have one single return at the bottom of the function. That helps avoid problems with cleanup (e.g., freeing of memory) that might be allocated in the workings of the function.
There's nothing inherently wrong about having more than one exit point, especially when you're returning on errors. Returning immediately usually makes for clearer code than having the whole thing wrapped in an if/else statement and setting some result flag to be returned at the end. (When you see "return result;", you have to look through all of the earlier code to see how and when result gets set. More moving parts == less clarity.)
You've tagged your questions as "C" which makes a difference.
In C you might write code such as
open file
process data
close file
If you put a return in the middle of the process data section then you're likely to skip the essential cleanup so it might be considered bad practice to have multiple return points because it's very easy to mess up.
If it was C++ then its best practice to let destructors handle cleanup so it's not nearly such a potential problem so this advice is somewhat obsolete in c++
As Oded and Andrzej Doyle pointed out there is nothing wrong with it.
They is no such thing as a golden rule when it comes to this.
The first an most important thing you have to keep in mind when writing code is that some one else will have to read it and make sense out of it. Maybe you will have to go about it in a couple of months, and if you have made a mess you will regret it.
Personally I always:
if the code is new used the coding style everybody else is using in the project.
If editing others code used the coding style already implemented there.
Avoid above all code optimizations (the compiler is best at that).
keep it clean and lean.
If your function is small enough (10-15 lines), as it should be :), then it really doesn't matter if you use a single return point or multiple one. Both are equally readable.
Problems start cropping up with badly designed large functions. In such cases both the styles, returning from a single point, and returning from multiple points, further complicates the function, although even in such cases I prefer returning early and returning at multiple points.
It's often the case that you have to check for several conditions etc before you start with the real work, and then you are tempted to do an early return, as in your code. I think this is fine for short methods, but when it gets more complicated I'd suggest to break your code in a "setup and check" method and a "real work" method, both having only one exit. Of course as long as it's readeable, it's fine to have multiple returns (e.g. in a long switch statement).
Failing (and thus returning) early is a very very very good practice. All the code after the checks is free of a lot of potential errors.

Resources