ProgrammingModerate

Which loop is safe for every value a plain char can hold, including bytes above 127 that may be negative?

  1. A. for (char *p = s; *p; p++) *p = toupper(*p);
  2. B. for (char *p = s; *p; p++) *p = (char)toupper((unsigned char)*p);
  3. C. for (char *p = s; *p; p++) if (isalpha(*p)) *p -= 32;
  4. D. for (int i = 0; i < 26; i++) s[i] = toupper(s[i]);

Correct answer: B. for (char *p = s; *p; p++) *p = (char)toupper((unsigned char)*p);

isalpha and toupper require a value representable as unsigned char or EOF. Passing a negative char is undefined, so the value is converted through unsigned char first.

More C Programming questions

Exams that ask this topic