Skip to main content
added 808 characters in body
Source Link
Cliff B
  • 69.3k
  • 4
  • 33
  • 56

wouldn't the inner loop work better if it incremented j instead of i? ;-)

Programming tip: Look at the for loop setup:

    for(int j = i + 1; j < strlen(key); i++)

It's better to set a var equal to strlen when used in a for loop for two reasons. First, when it's written like that, strlen is called on every pass of the loop, using up cpu cycles. Second, if the string "key" is altered in such a way that a char is changed to 0x00, that would be interpreted as the end of string marker and the loop would end prematurely.

The best practice is to use this form:

    for(int j = i + 1, keylen = strlen(key);  j < keylen; i++)

In this form, strlen is calculated exactly once, before the first pass, and can never change (as long as keylen remains unchanged.) It saves cpu cycles and prevents the string length from changing throughout the loop execution.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

wouldn't the inner loop work better if it incremented j instead of i? ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

wouldn't the inner loop work better if it incremented j instead of i? ;-)

Programming tip: Look at the for loop setup:

    for(int j = i + 1; j < strlen(key); i++)

It's better to set a var equal to strlen when used in a for loop for two reasons. First, when it's written like that, strlen is called on every pass of the loop, using up cpu cycles. Second, if the string "key" is altered in such a way that a char is changed to 0x00, that would be interpreted as the end of string marker and the loop would end prematurely.

The best practice is to use this form:

    for(int j = i + 1, keylen = strlen(key);  j < keylen; i++)

In this form, strlen is calculated exactly once, before the first pass, and can never change (as long as keylen remains unchanged.) It saves cpu cycles and prevents the string length from changing throughout the loop execution.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

Source Link
Cliff B
  • 69.3k
  • 4
  • 33
  • 56

wouldn't the inner loop work better if it incremented j instead of i? ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)