Where to format/place the "{" in C? [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 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.

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.

Counter variables in loops [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 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.

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.

Which is the best place for parameter restrictions - inside or outside function? [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
Option 1: In function
int funcA(int a){
if(a < 0){
return -1;
}
else{
...
return 0;
}
}
Option 2: In main
int main(){
int a;
...
if(a < 0){
...
}
else{
funcA(a);
}
}
Option 3: Both places? If you have some suggestions I will be grateful.
There is no hard and fast rule as to what is better -- there's basically two cases you'd want to consider.
If the constraints are unique to this specific usage of the function, then it would be preferable to put them outside the function, to let the function be more generalized and limit only this specific call to it.
If the constraints are something integral to the function and are always going to be expected whenever the function is called, then it would be preferable to put them inside the function, so that they do not have to be duplicated every place that the function will be called.
It is the callers responsibility to make sure it calls a function with valid arguments - per the documentation.
It is the called functions interest to guard against invalid values when it can - and again, per the documentation.
There is no inherently "right" or "wrong" choice without a contract (documentation) for funcA which is highly dependent on what the function does and how it is expected to be used.

Why a for loop isn't considered 'stylish' by my teachers? [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
I had to write a piece of code which would search a given value in an array.
I made this piece of code, which works:
#include <stdio.h>
int index_van(int searchedValue, int array[], int lengthArray)
{
int i ;
for (i = 0; i < lengthArray; i++)
{
if (array[i] == searchedValue)
{
return i;
}
}
return -1;
}
int main()
{
int array2 [] = {0, 1, 3, 4, 5, 2};
printf("%i", index_van(2, array2, 6));
}
With the correction (the teacher put up online) of this exercise the notes of my teacher were:
You have to quit the moment you have found your value ,so you can't search through the entire table if you have found your value already. A for-loop therefore isn't tolerated.
Even if the for-loop has an extra built-in condition, THIS ISN'T STYLISH!
// One small note ,she was talking in general . She hasn't seen my version of the exercise.
So my question to you guys is, is my code really 'not done' towards professionalism and 'style' ?
I think she's implying that you should use a while loop because you don't know how many iterations it will take to get you what you're looking for. It may be an issue of her wanting you to understand the difference of when to use for and while loops.
"...Even if the for-loop has an extra built-in condition..."
I think this right here explains her intentions. A for loop would need a built-in condition to exit once it's found what it's looking for. a while loop already is required to have the condition.
There is nothing wrong with your code. I have no idea if using a for loop is less stylish than using another, but stylish is a very subjective attribute.
That being said, don't go to your teacher and tell her this. Do what she says, a matter like this is not worth contradicting your teacher for. Most likely this is just a way to teach you how while loops work.
After accept answer:
I've posted this to point out sometimes there is so much discussion of "style", that when a classic algorithmic improvement is at hand, it is ignored.
Normally a search should work with a const array and proceed as OP suggest using some loop that stops on 2 conditions: if the value was found or the entire array was searched.
int index_van(int searchedValue, const int array[], int lengthArray)
But if OP can get by with a non-const array, as posted, then the loop is very simple and faster.
#include <stdlib.h>
int index_van(int searchedValue, int array[], int lengthArray) {
if (lengthArray <= 0) {
return -1;
}
int OldEnd = array[lengthArray - 1];
// Set last value to match
array[lengthArray - 1] = searchedValue;
int i = 0;
while (array[i] != searchedValue) i++;
// Restore last value
array[lengthArray - 1] = OldEnd;
// If last value matched, was it due to the original array value?
if (i == (lengthArray - 1)) {
if (OldEnd != searchedValue) {
return -1;
}
}
return i;
}
BTW: Consider using size_t for lengthArray.

Resources