ProgrammingModerate
Which loop is safe for every value a plain char can hold, including bytes above 127 that may be negative?
- A. for (char *p = s; *p; p++) *p = toupper(*p);
- B. for (char *p = s; *p; p++) *p = (char)toupper((unsigned char)*p);
- C. for (char *p = s; *p; p++) if (isalpha(*p)) *p -= 32;
- 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
- What is the smallest array size that holds the string "Ravi" with strcpy and no undefined behaviour?
- char s[] = "x41x420x43"; printf("%zu", strlen(s)); What is printed?
- char s[] = "banana"; char p = strrchr(s, 'a'); printf("%ld", (long)(p - s)); What is printed?
- printf("%zu", strcspn("aXbYc", "XY") + strspn(" 42ab", " 0123456789")); What is printed?
- A naive strstr-style search looks for a pattern of length m = 50000 in a text of length n = 100000. The text is all 'a' and the pattern is…
- What does strncmp("abc", "xyz", 0) return?