While I was putting together a to-uppercase function in C++ I noticed that I did not receive the expected output in C.
C++ function
#include <iostream> #include <cctype> #include <cstdio> void strupp(char* beg) { while (*beg++ = std::toupper(*beg)); } int main(int charc, char* argv[]) { char a[] = "foobar"; strupp(a); printf("%s\n", a); return 0; } Output as expected:
FOOBAR #include <ctype.h> #include <stdio.h> #include <string.h> void strupp(char* beg) { while (*beg++ = toupper(*beg)); } int main(int charc, char* argv[]) { char a[] = "foobar"; strupp(a); printf("%s\n", a); return 0; } The output is the expected result with the first character missing
OOBAR Does anyone know why the result gets truncated while compiling in C?
toupper() function in C The toupper() function is used to convert lowercase alphabet to uppercase. i.e. If the character passed is a lowercase alphabet then the toupper() function converts a lowercase alphabet to an uppercase alphabet. It is defined in the ctype.
toupper() works on one element ( int argument, value ranging the same as of unsigned char or EOF) at a time. Prototype: int toupper(int c); You need to use a loop to supply one element at a time from your string.
The toupper() function converts the lowercase letter c to the corresponding uppercase letter. Both functions return the converted character. If the character c does not have a corresponding lowercase or uppercase character, the functions return c unchanged.
JavaScript String toUpperCase() The toUpperCase() method converts a string to uppercase letters. The toUpperCase() method does not change the original string.
The problem is that there is no sequence point in
while (*beg++ = toupper(*beg)); So we have undefined behavior. What the compiler is doing in this case is evaluating beg++ before toupper(*beg) In C where in C++ it is doing it the other way.
while (*beg++ = std::toupper(*beg)); leads to undefined behavior.
Whether *beg++ is sequenced before or after std::toupper(*beg) is unspecified.
The simple fix is to use:
while (*beg = std::toupper(*beg)) ++beg;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With