-4

I have the following code

#include <stdio.h>

int main() {
    char y=3, res=0;
    res = ( (++y) * (++y) );
    printf("res=%d    y=%d \n", res, y);
    return 0;
}

The result is:

res=20    y=5

Now when i change variable to int it gives different results

#include <stdio.h>

int main() {
    int y=3, res=0;
    res = ( (++y) * (++y) );
    printf("res=%d    y=%d \n", res, y);
    return 0;
}

The result is:

res=25    y=5

What happened to make res value change?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Nasr
  • 2,482
  • 4
  • 26
  • 31

1 Answers1

1

What you're doing there is undefined behavior. If it were defined (either by the spec or by the implemetation), you'd get the same result no matter what data type you used. The value will also change due to optimization.

Paul Stelian
  • 1,381
  • 9
  • 27