c++ - subsructing getchar's return value -
suppose have file consists of single string
a1
if write this:
char ch = getchar(); char ch1 = getchar(); cout << ch - 'a' << " " << ch1 - '0' << endl;
i have 0 1
in output. if write this:
cout << getchar() - 'a' << " " << getchar() - '0' << endl;
i have -48 49
. doesnt getchar() return normal char? why result isn't same?
you're getting issue because 2 calls getchar()
evaluated in unspecified order, , compiler happens evaluate rightmost 1 first.
c++ has rather loose rules regarding order of evaluation of subexpressions in expression, allow more optimisation opportunities. cout
line 1 expression, following guaranteed:
- the first
getchar()
evaluated before first-
- the second
getchar()
evaluated before second-
- the first
-
evaluated before first<<
- the second
-
evaluated before third<<
- the
<<
s evaluated in order left.
note there no other ordering restrictions. example, compiler free evaluate both getchar()
calls , both -
s before first <<
. importantly, there no rule forcing first getchar()
evaluated before second one.
Comments
Post a Comment