Usage of ternary if [closed] - c

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
From Wikipedia, the following sections of code are equivalent:
if (a > b) {
result = x;
} else {
result = y;
}
And:
result = a > b ? x : y;
Obviously the use of the ternary if is much more concise, though not as clear.
What I'm wondering is: Is it bad (In terms of readability of code, execution time etc.) to use the ternary if instead of a traditional if statement?

It all depends. I can only think of one situation where a ternary operator undeniably improves readability and even performance (see bottom of this answer). But generally, using the ternary isn't going to improve readability/maintainability of your code. If you use it occasionally, and only for simple assignments then it's OK. not good, just acceptable IMO. Others are, of course, free to disgree with me on that.
Ternaries are expressions, so they should only be used as such (part of an assignment, for example). If you start using ternaries as statements, then you're in trouble. Ternaries are not statements, using them as such is like using a spoon as a screwdriver. Silly.
On the whole, though: it's a matter of taste as long as you don't overdo it. Once you start nesting ternaries, using them with pointers to pointers, or as statements, it's a matter of lunacy.
But to be honest: when in doubt: don't use the ternary operator. It saves you 1 line of code and doesn't improve performance. Take your example:
if (a > b) result = x;
else result = y;
//vs:
result = a > b ? x : y;
if result is the return value of a function, you could even write:
if (a > b) return x;
return y;
Even though I now have 2 return statements, I still find this code easier to read than:
result = a > b ? x : y;
//or
return a > b ? x : y;
That one use-case where a ternary is the best option is this:
const int two_options = some_arg ? 23 : 1;
This enables you to define + initialize a const within a function's scope, depending on a condition, without the overhead of an additional function call (const int two_opts = arg_func(some_arg);, where the function contains the if-else)

Related

Dangling else query (or an excercise in reading bad code) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
The book I'm reading (C How to Program with an into to C++ Global Edition, Deitel&Dietel, 2016) gives the following code: Note that this is how the book presents the code in the exercise section, without braces and indentation on purpose. I would assume to teach you that using correct indentation makes reading code a lot easier.
int main(){
int x = 9, y = 11;
if (x < 10)
if (y > 10)
puts("*****");
else
puts("#####");
puts("$$$$$");
}
The output is
*****
$$$$$
The book states the compiler always associates an else with the previous if unless told to do otherwise by the placement of braces so by that logic the else is associated with
if (y > 10)
which is true and the else shouldn't execute, giving an output of
*****
and not
*****
$$$$$
So my question is why is the line
$$$$$
in the output?
[too long for a comment]
Even without braces it is quite clear what goes where if indented and new-lined properly (which can be automated, BTW):
int main() {
int x = 9, y = 11;
if (x < 10)
if (y > 10)
puts("*****");
else
puts("#####");
puts("$$$$$");
}
You wrote this (equivalent to yours)
if (x < 10) {
if (y > 10) {
puts("*****");
}else{
puts("#####");
}
}
puts("$$$$$");
And it is following what you said. The else matches with the closest if. Here y>10. And the if and else always consider the single statement when we don't use brackets. Here if-else block inside the outer if serves the purpose of the single statement. Same way the for the else the single puts("####") serves the purpose. The last puts will be executed no matter what the value of x and y be.

Where to format/place the "{" in C? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Can anyone explain me please why here:
void
st_clear(st_table *table)
{ //1 a new line
register st_table_entry *ptr, *next;
st_index_t i;
if (table->entries_packed) { //2 the same line
table->num_entries = 0;
table->real_entries = 0;
return;
}
for (i = 0; i < table->num_bins; i++) {
ptr = table->bins[i];
table->bins[i] = 0;
while (ptr != 0) {
next = ptr->next;
st_free_entry(ptr);
ptr = next;
}
}
table->num_entries = 0;
table->head = 0;
table->tail = 0;
}
in one case they left { of the same line, whereas in another put to the new line?
https://github.com/ruby/ruby/blob/1b5acebef2d447a3dbed6cf5e146fda74b81f10d/st.c
I know in C there's no a definite naming convention like in most other languages, yet { within one project always has to be put either on the new line or left on the same line.
There's nothing in the C standard itself that mandates placement of tokens, provided they're in the right order. In fact:
i
= j
++;
is perfectly okay, syntax wise, despite it being seriously ugly formatting for:
i = j++;
Having said that, you should stick to your guidelines as much as possible. In this case, we don't actually know what the guidelines are.
It's entirely possible that the guidelines state different brace placement for functions and non-functions.
As you noted, this is completely valid, and is indeed part of many common indentation-styles, e.g. K&R-style (Wikipedia has a summary of some popular styles).
Why this is done in this case, is hard to answer without the coding-style guidelines (with some rationale) being followed for this code, but an advantage is, that there is a function definition if and only if there’s a line matching ^[{], so they can be found easily. (Functions do not nest in standard C, so the { is always at the first column, and there (apparently) aren’t any other constructs where a { is at the first column in this coding style convention.)
As mentioned in the Wikipedia article linked above, old-style definitions may have been another (though historic) reason for this convention to become popular.
The { introducing a function definition is different from other braces at the beginning of a compound statement, in that it is required (function bodies are the only case where a compound statement cannot be replaced by some other statement, int foo(void) return 5;, for example, is invalid). This may somewhat legitimate the inconsistency (if you consider it such) with the placement of other braces in different circumstances.

Refusing to use <= in C [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have this habit in C (and many other languages) where rather than foo <= bar I will do foo < bar + 1 and no idea where this even came from...
Is this bad, per se, or just nonstandard? I mean from the context of coding and later modifying the code...I assume any good compiler compiles both of them the same.
This is bad for multiple reasons:
Does not work for floating point numbers
Does not work for signed numbers (-2.5 <= -3 is false, but -2.5 < -3 + 1 is true)
Makes your code difficult to understand
Increases the chances that you'll (needlessly) create an overflow error
It's bad and nonstandard. There's really no reason to continue reinforcing the habit - you're just shooting yourself in the foot for later in your coding career.
I think it's less clear, personally. Also it could be bad if foo and bar are not integers; for example the two will mean something different if foo= -7 and bar = -7.5.
Based on your comment:
it helps prevent errors with how many iterations of loops take place
You're most likely referring to looping in these two ways:
Method I:
for(int i = 0; i < length; i++){ // } which would go between 0 and length-1.
Versus:
Method II:
for(int i = 0; i <= length-1; i++){ //} which also goes between 0 and length-1.
In these particular cases, either will work, but as Derek Redfern outlined in his answer above, don't make your code any more complicated than it should be.
It is very broken, especially when you do
int foo = <whatever>;
int bar = INT_MAX;
if (foo < bar + 1) {
/* guaranteed to never be called */
}
Also, it is likely to break if you "adjust" it in the other way, like so
int foo = INT_MIN;
int bar = <whatever>;
if (foo - 1 < bar ) {
/* again guaranteed never to be called */
}
In short, far better to check for equal and greater (or equal and less than) than to create code that adjusts a value during the comparison.

Is there a difference between using a[i] and *(a + i)? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Both a[i] and *(a + i) access the i th element of array a.
Are there reasons to prefer one over the other(performance, readability, etc...)?
Neither one is better from a language point of view since they are the same, array indexing should just be syntactic sugar for pointer arithmetic. We can see this from the draft C99 standard section 6.5.2.1 Array subscripting which says (emphasis mine):
[...]The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).[..]
Although for others reading your code a[i] is probably more readable.
a[i] should be preferred, because it is more commonly used and so will be understood more quickly by the person reading the code.
Although they are identical in arrays, I prefer a[i] for the following reason. Suppose you have code like this:
double gradient[3];
// 200 lines later
double dx = gradient[0]; // Works fine
double dy = *(gradient + 1); // Works just as well
Then somebody decided that std::vector looks better than double[]:
vector<double> gradient;
// 200 lines later
double dx = gradient[0]; // Still works
double dy = *(gradient + 1); // Ouch!
Then somebody else decided to go object-oriented all the way:
class Gradient
{
public:
double operator[](int index) const;
};
// 1000 lines later
Gradient gradient;
// 200 lines later
double dx = gradient[0]; // Still works
double dy = *(gradient + 1); // Ouch!!!
Thus, from the viewpoint of maintainability, I prefer to say exactly what I mean, without obscuring the intent with context-dependent synonyms. If I mean "take i-th element of a" then I say exactly that in C++ lingo:
a[i];
rather than relying that for the particular implementation of a one can use a fancier expression for the same.
C has no operator overloading. So you are safe to use whichever you want.
I would use a[i] for clarity when reading the code.
Both are equivalent. Neither one is preferred over other but a[i] is commonly used by programmers. a[i] = *(a + i) = i[a]
As far as I'm concerned (just finished a C course), there is no difference.
Array is implemented as a pointer to the first element on the stack. So a+1 is just the address on the stack after a :)
Edit:
Also, as mentioned by John Bartholomew, even though they are the same, you might want to use a[i] instead - that is the "normal" way to do it (also in other languages) :)
For readability purposes, I would definitely go with a[i].

Does for loop in c only can have one statement? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Ruby's for/in loop can have many statement:
for a in 1..2 do
expression 1
expression 2
..
end
But it seems for loop in C can only have one:
for (a = 0; a < 10; a ++) expression 1;
Is there any way to make multiply statement in the for loop in C?
Yes, formally speaking all loop statements in C take only one statement as the loop body. The same is true for branching statements (like if) and virtually all other statements in C.
However, that one statement can be a compound one. A compound statement begins with {, ends with } and contains an arbitrary number of nested statements inside. (Note that there's no ; at the end of compound statement.)
Use braces for the body of the loop:
for (a = 0; a < 10; a++)
{
doSomething();
doSomethingElse();
}
This concept extends to other things, like if, as well. This should be mentioned right alongside the if and for themselves in any book, etc.
You need to learn C syntax. You put them in a block
for (...) {
expression 1;
expression 2;
}

Resources