Counter variables in loops [closed] - loops

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 6 years ago.
Improve this question
Which one of the following two is better in terms of good programming design, speed, efficiency and memory point of view?
1)
for(int i=0;i<10;i++)
{
...
}
2)
int i;
...
...
for(i=0;i<10;i++)
{
...
}
I mean, if there are many such (or maybe different) loops in program, then which one should be used?

Definitely the first one.
It is more concise and clear;
The variable i will be visible only inside the for block;
Try to never micro-optimize unless you really need it.
Quote from Java docs :
If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression.
In Java 8 you can also do this :
IntStream.rangeClosed(1, 10).forEach(System.out::println);

If you don't need to access i outside of the loop, it should be inside the loop. If you put it inside the loop, it is destroyed when the control goes out of the loop, which saves memory. Also putting i inside the loop will make the code more readable.

The both are bad because they use magic number 10.:)
As for which loop to use then it depends on the context: whether variable i has to be used outside a loop.
If so then I would write
int i;
...
...
i = 0;
for ( ; i < 10; i++ )
{
...
}

in this scenario.....
Note :-There is no performance issue in both program ...
But only if we can talk about scope of i then First loop is better if there is no requirement of i beyond the loop and If not Needed then you should declare it as per you 2ond Way of Code

(This is for Java)
Use "int" keyword outside of loop if you want to access it after/before the loop. But if you use it outside I recommend using "while" loop, and adding a one to the int each time. You don't need to assign int variable to 0, since int can't be null, and by default is 0.
int i;
...
...
...
while (i < ***){
...
i++;
}
2nd variant is only useful if you break the loop if there something happened, so you can get how many iterations happened later on.

If you wanna use i again after the usage of for like the code below, then go with second one.
int i;
for (i = 0; i < length; i++) {
...
}
}
if (i > 50) { /* your code */ }
However, if you do not need to use 'i' after the usage of for, then go with the first one for the sake of memory usage and simplicity.

Which one of the following two is better in terms of good programming design, speed, efficiency and memory point of view?
In Java you can use both, in C before C99, you can only use the 2nd approach.
As for your question:
good programming design: 1 is better as the variable x was only used and meant for the loop, thus enclosing it within scope of the loop will be a better design.
speed: Both the same
efficiency: Both the same
memory: 1 is better since the variable will readily to be discarded after use within the loop.
User Alter Mann brought up a good point about portability for using the 2nd approach.

Related

is it bad practice to call a function from within an if condition? [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 1 year ago.
Improve this question
hello< I am working on my first solo project in C and I have a bunch of sanity checks which call functions that return a bool. My question is it bad practice to call the the function from within the if condition or should I assign it's return value to a bool variable then use that variable in the condition. I'm teaching myself how to code and I am trying not pick up any bad habits. Below is a code example.
// This function checks user input for allowed operation
// MAX_OPERATIONS is a macro that defines the max number of operations allowed
bool check_operation(char *n, char **ops)
{
for (int i = 0; i < MAX_OPERATIONS; i++)
{
if (strcasecmp(n, ops[i]) == 0)
return true;
}
return false;
}
// In main I call it like this
// operations_arr is an array of pointers that stores the operations
// allowed in string format
if (!check_operation(argv[1], operations_arr))
{
error_message();
return 1;
}
There's nothing wrong with it. Though many C functions involve checking the result of parameters rather than the returned value and then you have no other option but to call the function on a line of its own.
Also, this is a common scenario:
result_t result = func();
if(result == ERR1)
...
else if(result == ERR2)
...
Here you can obviously not write
if(func() == ERR1)
...
else if(func() == ERR2)
...
Because then you end up calling the function twice, which is inefficient, but could also give different results.
As for using return from a function as a way to quickly stop executing and go directly to the error handler, it's actually likely the best way of doing so in C. Other alternatives are using messy boolean flags in the loop, or the "on error goto" pattern (which is usually OK but comes with the mandatory, tiresome "goto considered harmful" debate).
As for picking up bad habits: not using const correctness of read-only parameters is a bad habit.
There's nothing wrong with it as such, but I'd argue it's better to assign it to a variable because by doing so you're writing explicit code.
Explicit code is easier to read and also easier to maintain. Right now you're returning a bool, but imagine in future you change your function to return an int in order to pass more information, then you'd possibly want to add more checks. Also, by assigning its value to an explicitly typed variable you're making it easier for compiler to do some basic type checking to guard you from errors that might arise from changing the return type of the function.

Can someone help me understand how this "for" loop works? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
int main(void) {
long fall, n, k, p, i, j, r;
long long x, y, a[110][110];
for(a[0][0]=scanf("%ld",&fall);fall--;printf("%lld\n",y)) {
for(i=!!scanf("%ld%ld%ld",&n,&k,&p);i<=k+1;i++)
for(j=0;++j<=i;a[i][j]=(a[i-1][j-1]+j*a[i-1][j])%p)
;
for(y=!(j=1);j<=k+1;y=(y+a[k+1][j++]*x)%p)
for(x=!((r=n%j)*!(i=-1));++i<j;x=x*(n-i)/((i==r)?j:1)%p)
;
}
return 0;
}
How does for loop work here? It doesn't follow the syntax as I see.
for loops have the following pattern:
for(initial expression; conditional expr; afterthought)
I'll break down the first loop for you, you should be able to do the rest on your own.
for(a[0][0]=scanf("%ld",&fall);fall--;printf("%lld\n",y))
The initialization part of this loop is a[0][0]=scanf("%ld",&fall).
scanf is used for reading input and returns the number of input values. In this case, it will be 1 and it gets assigned to a[0][0].
fall-- is the conditional expression. In C, positive numbers are evaluated as true. So this loop will run until fall == 0.
printf("%lld\n",y) is the afterthought. It gets run after each loop iteration. In this case, it will simply print the value.
Unraveling obfuscated code can be a good learning exercise though you must obviously never use it in practice.
This code abuses the fact that the first and third conditions of the for loop does not necessarily need to have anything to do with the loop itself. At its core, the for loop simply executes an initial expression, performs the conditional check and executes the afterthought after every iteration.

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.

What is the idiomatic way to break out of a recursion 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 6 years ago.
Improve this question
Suppose we have a recursive function, f, that might fail if the input is incorrect. The error in the input can only be detected while f is running.
What is the idiomatic way in C to break out of f(), straight to the original calling function, in case of an error?
Is setjmp/longjmp the usual solution here?
Toy example:
void g() {
int arr[] = {1, 2, -3, 4};
int result = f(0, sizeof(arr)/sizeof(int) - 1, arr);
/* if f() was successful: */
printf("%d\n", );
/* if error occurred in f: do something else */
}
int f(int n, int i, int *arr) {
if (i < 0)
return n;
/*
if (arr[i] < 0) <-- "erroneous input"
break to g()
*/
return f(arr[i] + n, i-1, arr);
}
Options are:
Return a status flag from f() indicating success or failure. This causes the error to bubble up one level at a time from the depth at which the error occurs, so may not be what you want. Note that this is the only safe option if you need to unwind any allocations or release resources which f() may have claimed at each level.
Use setjmp() and longjmp() exactly as you suggest to simulate the effect of throwing an exception and jump directly to the error-handling code.
The usual way is it return a value indicating an error, mostly -1 is used.
I think longjmp is the way to go. I would not at all consider it good coding style, though.
It becomes harder to see what your code does if you start introducing jumps in it. There are also numerous problems:
code readability suffers
you can only call your function from one place, thus reuse of the code is severely limited
it's easy to introduce memory leaks when using longjmp
the resulting code is much more brittle (breaks easier, for example when introducing some piece of code above the setjmp)
Unless you have very specific performance requirements, try to avoid it and instead let an error result bubble back down to your original caller.
If the recursion will be deep, I would think longjmp makes more sense. Otherwise returning costs an extra O(N) (where N is the number of levels of recursion), and that includes thrashing the cpu cache with tons of pages of stack frames (each stack frame is likely to be a whole cache line).
Some will argue that longjmp is "bad style", and I will agree, but using deep recursion is much worse style already anyway... (And likely to have much worse effects, like blowing away your stack and crashing the program or yielding privilege compromise, not just looking ugly.)

Resources