Answer: Let’s first consider examples below,
int stud_passed[5] = {234, 11, 456, 99, 887}; int *pi; int i;
Now, we try accessing the array ‘stud_passed[]’ using subscript and ptr-to-int, ‘pi’
for (i = 0; i < 5; i++) stud_passed[i]; /* using subscript */ for (pi = stud_passed, i = 0; i < 5; i++, pi++) *pi; /* using ptr-to-int */
Now, question is Which of the two is more efficient? Let’s unravel one by one, accessing the array ‘stud_passed[]’ using subscript indicates that ‘stud_passed[5]’ is a pointer constant so it can’t be modified, i.e. expression,
stud_passed++; /* 'stud_passed' is pointer constant */
doesn’t worth for any meaning and results in error. Further, during each iteration through for loop, index i changes. In first iteration,
stud_passed[0 * 4]; /* index i with value 0 is being scaled to type int */
during 2nd iteration,
stud_passed[1 * 4]; /* i is 1 */
during 3rd iteration,
stud_passed[2 * 4]; /* i is 2 */
and so on till for statement exits. This requires, in each iteration, i to be updated and scaled to integer followed by addition to the base address of the array and finally subscript operator performs to evaluate the value.
While using pointer ‘pi’ to access array ‘stud_passed[]’, multiplication and addition like arrays above are also performed and that in adjustment statement. But here’s a difference that through each iteration, statement
pi++; or pi = pi + 1; /* 'pi' is pointer variable */
is incremented by same value (1 * 4). Further, this is computed once at compile time and so there are less no. of instructions executing at run time resulting in efficient code than using subscript.
Notice, however, that code fragment using pointer could be written more concisely as below,
for (pi = &stud_passed[0]; pi < &stud_passed[5]; ) *pi++;
But one shouldn’t compromise with Program Readability and Maintainability for smaller gains in efficiency.
Let’s take another example, where pointer and subscript are equally efficient,
float rain_fall[5]; float *fp; int i; for (i = 0; i < 5; i++) rain_fall[i] = 0; /* clearing array 'rain_fall[]' */
using the ptr-to-float ‘fp’,
for (i = 0; i < 5; i++) *(fp + i) = 0; /* clearing array 'rain_fall[]' */
In general, code with pointers can be more efficient than with subscripts but code with subscripts can’t be more efficient than with pointers.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Practice BCA MCQs
- Check Computer Science Books
- Watch Advanced C Programming Videos
- Apply for C Internship
- Check C Books