rsarson
rsarson

Reputation: 95

Different methods of printing text using subscripts

Are there any significant differences between the following two methods of printing text using subscripts? Are there any pros/cons of using one method over the other?

#include <stdio.h>

int main(void)
{
    int i;
    char *text;

    /* method 1 */
    text = "abc";
    for (i = 0; i < 3; ++i) {
        printf("%c\n", text[i]);
    }

    printf("\n");

    /* method 2 */
    for (i = 0; i < 3; ++i) {
        printf("%c\n", "abc"[i]);
    }

    return 0;
}

Upvotes: 0

Views: 51

Answers (1)

Alexandre FERRERA
Alexandre FERRERA

Reputation: 413

Both methods are basically the same. The 2nd method could be slightly faster since your print function calls a static value ("abc") instead of a reference to "abc".

I wouldn't be surprised if the compiler would make those 2 methods similar in the end.

This being said, the first method should be better in most situations since you'll probably want to reuse the 'text' variable or load it from elsewhere.

Upvotes: 1

Related Questions