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
C function
#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?
C++
:std::transform(a, a + strlen(a), a, std::toupper);
– Resupinate=
to be evaluated before the left? – Rainboltwhile (*beg = toupper((unsigned char) *beg)) beg++;
.toupper()
is not well defined for negativechar
values. – Gutbucketstd::transform
state that "std::transform does not guarantee in-order application of unary_op or binary_op. To apply a function to a sequence in-order or to apply a function that modifies the elements of a sequence, use std::for_each". – Warslestd::for_each(a, a + strlen(a), [](char &c){ c = std::toupper(c); });
? – Warslestd::transform
. – Resupinate