Is there a difference between using a[i] and *(a + i)? [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
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].

Related

I don't know what to put in the place of β and α in order to print all 3 digit numbers different from 0 and unique [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 3 years ago.
Improve this question
I don't get what I should put in the place of: "α" and "β" in order to print all the 3 digit numbers which are different from 0 and from one another.
It is required to replace those 2 variables, with some code
We are entering G(0)!!!
It's from an exam paper, I really don't get it, please help.
void G(int k)
{int i;
for(i=1;i<=α;i++)
{ p[k]=i;
if(β)G(k+1);
else
printf("%d%d%d\n",p[0],p[1],p[2]);
}
}
For any of this to make sense, it must be that p is declared as a global int array of dimension at least 3. I assume for the purposes of this answer that it is in fact so declared.
Note that the function sets p[k] = i, but it later reads back only p[0], p[1], and p[2]. This should give you a pretty good idea about what makes sense for expression β, which controls whether to recurse (increasing k) or print.
Note also that the function sets p[k] = i, and that when it reads back those p[k] for various k, it wants to get values ranging from 1 to 9 (no more and no less). This should give you a pretty good idea of what expression makes sense for α, the inclusive upper bound on i.
Having figured those out, it remains to satisfy yourself that the natural substitutions for those expressions indeed produce a resulting function that behaves as required when initially called as G(0). I suspect that you will find that easier than you did discerning the needed expressions.
(Details are left as an exercise.)

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.

Is pointer arithmetic hard? [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 remember when I first started learning C somebody told me that "pointer arithmetic is hard." I don't exactly understand what is hard about it though?
arr[i] == *(arr + i)
*ptr = arr[2] then *ptr + 1 = arr[3]
Is this really all there is to it, because neither of these concepts is as hard as I expected?
Well, if you mean *(ptr + 1) = arr[3] for that last one, then it seems like you have the hang of it. Making the substitution of the subscript operator ([]) for a pointer:
arr[3] === *(arr + 3)
Isn't very difficult. What gets tricky is when you have pointers point to the middle of an array, and then have to remember where they are in the array so you know what to index. So if ptr1 points to the beginning of an array, and ptr2 points at index 3, then *(ptr1 + 4) and *(ptr2 + 1) each yield the same value. In addition, if you have pointers in the middle of an array, you can subscript with negative numbers, something that isn't allowed in higher level languages like Java. So yes, it can get as complicated as one cares to make it.

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.

Usage of ternary if [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
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)

Resources