0

I tried to compile this on CodeBlocks (version 13.12). Somehow, the pointer is incremented before it is called by toupper()

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


int main(void)
{
 char str[80] = "the only way";
 char *p;

 p = str;

 while(*p){
    *p++ = toupper(*p);
 }

 printf(str);
 return 0;
}

This leads to the output "HE ONLY WAY" where as I am looking for the output "THE ONLY WAY". I tried it on my computer where it gives the wrong output. However, when I tried this code on a friends computer the code ran fine, giving the output "THE ONLY WAY". My question is why does my output differ? P.s If I replace

*p++ = toupper(*p);

with

*p++ = toupper( *(p-1));

I get the desired output of "THE ONLY WAY".

utopia123
  • 3
  • 2
  • 2
    'Unexpected output, but code is not wrong' This title is a contradiction. Clearly, if the output is unexpected, then the code is likely incorrect. A much more helpful title will describe what the *actual problem* is. – aruisdante Dec 14 '14 at 19:12
  • Sorry, will keep that in mind in the future – utopia123 Dec 23 '14 at 06:55

2 Answers2

2

Your code is causing undefined behaviour. It is not valid to refer to a pointer more than once in the same statement if you are using the pre- or post- increment/decrement operators.

Change your code to:

*p = toupper(*p);
p++;

This will ensure that the pointer p is changed only after you have used it.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0

According to the C Standard (6.5.16 Assignment operators)

3 .. The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

So your program has undefined behaviour.

For example MS VS 2014 outputs as you expected

THE ONLY WAY
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335