Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!bloom-beacon!athena.mit.edu!scs From: scs@athena.mit.edu (Steve Summit) Newsgroups: comp.lang.c Subject: Re: Array indexing vs. pointers... Message-ID: <7131@bloom-beacon.MIT.EDU> Date: 20 Sep 88 05:47:58 GMT References: <8809191521.AA17824@ucbvax.Berkeley.EDU> Sender: daemon@bloom-beacon.MIT.EDU Reply-To: scs@adam.pika.mit.edu (Steve Summit) Lines: 45 WARNING: Heretical C advice follows. Efficiency hackers please read no further. In article <8809191521.AA17824@ucbvax.Berkeley.EDU> Michael J. Steiner writes: >How and why is array indexing slower than pointer arithmetic? >I think that compilers should automatically translate array indexing >into pointer arithmetic when dealing with arrays in C. Array indexing may be slower, but it may also be easier (for human readers of the program) to understand. If there is the slightest chance that using array indexing instead of pointers will make your code clearer, I'd like to encourage you to stick with the indices, unless your program ends up running too slowly, and profiling shows the array indices to be at fault. Chances are it won't run noticeably slower, in part because there are good compilers which, in the spirit of your suggestion, effectively use a pointer reference in the generated code. This is not to say that array indexing is always clearer than pointers--often, a well-conceived pointer algorithm is the right one to use for both clarity and efficiency. It's a judgement call. But some code is just ridiculously clearer to the uninitiated if it uses indices rather than pointers, and at no cost in overall efficiency. A perfect example is argv parsing; compare while(--argc) if(**++argv == '-') processoption(*argv); else processfile(*argv); with for(i = 1; i < argc; i++) if(argv[i][0] == '-') processoption(argv[i]); else processfile(argv[i]); The second example may use an extra variable, but it's a lot more obvious that argv[0] is skipped (as it should be) and it has the additional benefit of leaving the initial values of argc and argv undisturbed. Steve Summit scs@adam.pika.mit.edu