简体   繁体   中英

Why const char pointer assigned to another in C?

In compute_scrabble_value function const char word[] is assigned to const char *p .

#include <stdio.h>
#include <ctype.h>

#define MAX_LEN 30

int compute_scrabble_value(const char *word);

const int scrabble_values[26] = {1, 3, 3, 2,  1, 4, 2, 4, 1, 8, 5, 1, 3,
                                 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10 };

int main(void)
{
    const char word[MAX_LEN + 1];
    printf("Enter a word: ");
    scanf("%s", word);
    printf("Scrabble value: %d", compute_scrabble_value(word));
    
    return 0;
}

int compute_scrabble_value(const char *word)
{
   const char *p = word;
   int total = 0;

   while (*p) {
       total += scrabble_values[toupper(*p++) - 'A'];
   }
      
   return total;
}

But even if you don't assign like below, the output seems same.

int compute_scrabble_value(const char *word)
{
   int total = 0;

   while (*word) {
       total += scrabble_values[toupper(*word++) - 'A'];
   }

   return total;
}

Why is const char word[] assigned to another pointer variable?

There's no programmatic reason to do so; your code using word directly is equivalent.

But using word directly is mildly confusing to people reading the code; after the first pointer increment, word no longer points to the actual word, so if you later needed to refer to the word as a whole, you can't, but a maintainer might think you could because you still have word available. Making the copy into p avoids that semantic disagreement between the variable name and what it represents. An optimizing compiler would likely produce the same machine code anyway ( word is never used again, so word and p could be implemented as the same variable), and even if it didn't, as long as you're not running out of registers it hardly matters if it actually uses two different pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM