473,776 Members | 1,650 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

About C and order of evaluation

Hello, in the program below:

#include <stdio.h>

int main(void) {
int x = 1, y = 2, z;

z = x+++y;
return 0;
}

after executing, z has the value of 3, x is 2 and y is 2.

Can someone please explain me in detail why it is treated by the
compiler as (x++)+y and not for example as x+(++y) ?
What steps the compiler does to produce that result ?

Thanks for your time and sorry for my bad english

Charalampos Pournaris

Oct 8 '07 #1
13 1593
Richard Heathfield wrote:
Thus, z = x+++y; is parsed as

[z] [=] [x] [++] [+] [y] [;]
The compiler may be happy with that code but I sure wouldn't be pleased
if it showed up in a program I had to maintain. It _looks_ like a typo,
and without analyzing the surrounding lines there's no way to tell if:

z = (x++)+y;

or

z = x+(++y);

was intended. This is another one of those instances where C
is a little too flexible (for my taste) about the syntax it will accept.
Sometimes it would be better if the compilers warned the
programmers to put in a few more spaces or parentheses so that the
meaning of the code would be unambiguous. That is unambiguous without
having to know arcane details about the how the compiler's parser
functioned.

Here's Hello World with all "extra" spaces and EOL's removed.
It's down to just 3 lines and two spaces: one between "int" and "main"
and one between "Hello" and "world". My news client wrapped this after
the second space but in the original it was only a 3 line program.

#include <stdlib.h>
#include <stdio.h>
int main(void){(voi d)fprintf(stdou t,"Hello
world\n");(void )exit(EXIT_SUCC ESS);}

This 3 line form is legal but it's also really hard to read. It would
be nice if gcc (for instance) had at least an optional -Whuman, to issue
warnings for difficult to read but otherwise legal constructs.
Regards,

David Mathog
Oct 9 '07 #2
David Mathog wrote:
Richard Heathfield wrote:
>Thus, z = x+++y; is parsed as

[z] [=] [x] [++] [+] [y] [;]

The compiler may be happy with that code but I sure wouldn't be
pleased
if it showed up in a program I had to maintain. It _looks_ like a
typo, and without analyzing the surrounding lines there's no way to
tell if:

z = (x++)+y;

or

z = x+(++y);

was intended. This is another one of those instances where C
is a little too flexible (for my taste) about the syntax it will
accept.
Sometimes it would be better if the compilers warned the
programmers to put in a few more spaces or parentheses so that the
meaning of the code would be unambiguous. That is unambiguous without
having to know arcane details about the how the compiler's parser
functioned.
It's not the compiler's job to teach the programming best coding
practices. No one prevents someone from writing clear, well formatted
source. Unfortunately too many C programmers have IOCCC ambitions.
Witness the recent thread started by Antoninus Twink complaining about
a piece of clear C code.
Here's Hello World with all "extra" spaces and EOL's removed.
It's down to just 3 lines and two spaces: one between "int" and "main"
and one between "Hello" and "world". My news client wrapped this
after the second space but in the original it was only a 3 line
program.

#include <stdlib.h>
#include <stdio.h>
int main(void){(voi d)fprintf(stdou t,"Hello
world\n");(void )exit(EXIT_SUCC ESS);}

This 3 line form is legal but it's also really hard to read. It would
be nice if gcc (for instance) had at least an optional -Whuman, to
issue warnings for difficult to read but otherwise legal constructs.
This is a subjective decision and I think, though I'm not sure, it will
be rather hard to implement. This is something that the programmer must
learn from good books and peers, not a compiler, IMHO.

Oct 9 '07 #3
David Mathog wrote:
Richard Heathfield wrote:
>Thus, z = x+++y; is parsed as

[z] [=] [x] [++] [+] [y] [;]

The compiler may be happy with that code but I sure wouldn't be pleased
if it showed up in a program I had to maintain.
"It's specified. But anyone who writes code like that should be
transmogrified into earthworms and fed to ducks."

I can't find the original, only echoes in sign-quotes, alas.

--
Chris "transmogri fied ducks dollin" Dollin

Hewlett-Packard Limited registered no:
registered office: Cain Road, Bracknell, Berks RG12 1HN 690597 England

Oct 10 '07 #4
santosh wrote:
David Mathog wrote:
> Sometimes it would be better if the compilers warned the
programmers to put in a few more spaces or parentheses so that the
meaning of the code would be unambiguous. That is unambiguous without
having to know arcane details about the how the compiler's parser
functioned.

It's not the compiler's job to teach the programming best coding
practices. No one prevents someone from writing clear, well formatted
source. Unfortunately too many C programmers have IOCCC ambitions.
Witness the recent thread started by Antoninus Twink complaining about
a piece of clear C code.
Teach no, help with, yes. For the sake of argument, imagine that a
compiler had options like:

-Wfor_humans warn on difficult to read code
-Wstyle_fmt1 warn on source code not in specified style

Where the first would catch the "x+++y", and the second would pick up
on deviations from a specified coding style. These would be immensely
helpful, even if they have no effect whatsoever on the code generated.
Here is an example of the type of style variant I would love to be able
to flag.

if(some_conditi on)
do_something();

The lack of {} around the conditional code very often leads to errors
during code maintenance, and this can happen by accident when a stray
carriage return falls in the wrong place or an automatic line wrap
occurs unnoticed. Also, many projects have coding style standards, but
these are currently impossible to enforce using just the compiler. Some
projects want:
if(some_conditi on){
if(something_el se){
}
}
else{
}

and another may demand:

if(some_conditi on) {
if(something_el se) {
}
}
else {
}

It would be incredibly useful for me in these situations to be able to
throw a compiler switch to check for variation from these styles. The
compiler is clearly a good place to do this since it has to parse the
code thoroughly anyway, and could easily add a few more rules during
that parsing to pick up on things like indent levels, bracket spacing,
and split line if statements.

Regards,

David Mathog
Oct 10 '07 #5
David Mathog wrote On 10/10/07 12:12,:
santosh wrote:
>>David Mathog wrote:

>> Sometimes it would be better if the compilers warned the
programmer s to put in a few more spaces or parentheses so that the
meaning of the code would be unambiguous. That is unambiguous without
having to know arcane details about the how the compiler's parser
functioned .

It's not the compiler's job to teach the programming best coding
practices. No one prevents someone from writing clear, well formatted
source. Unfortunately too many C programmers have IOCCC ambitions.
Witness the recent thread started by Antoninus Twink complaining about
a piece of clear C code.


Teach no, help with, yes. For the sake of argument, imagine that a
compiler had options like:

-Wfor_humans warn on difficult to read code
-Wstyle_fmt1 warn on source code not in specified style

Where the first would catch the "x+++y", and the second would pick up
on deviations from a specified coding style.
The great difficulty is in describing the "style" not
only in precise terms, but in computable terms. As an
exercise, try modifying gcc or another compiler to issue
warnings for departures from

PRE31-C. Never invoke an unsafe macro with
arguments containing assignment, increment,
decrement, or function call
-- CERT C Programming Language Secure Coding Standard
http://www.securecoding.cert.org/

(This rather rough work-in-progress was discussed on c.l.c.
in August of this year.) It's easy enough to get the compiler
to recognize the listed operations, but I think you may have
difficulty teaching it to distinguish "safe" from "unsafe"
macros.
Here is an example of the type of style variant I would love to be able
to flag.

if(some_conditi on)
do_something();

The lack of {} around the conditional code very often leads to errors
during code maintenance, [...]
Aside: This assertion is "very often" made, but is it
backed by measurement? I've been omitting braces from one-
line consequents of `if' and `for' and `while' for more
than three decades, and can't recall coming to grief as a
result.
[...] Also, many projects have coding style standards, but
these are currently impossible to enforce using just the compiler.
[...] The
compiler is clearly a good place to do this since it has to parse the
code thoroughly anyway, and could easily add a few more rules during
that parsing to pick up on things like indent levels, bracket spacing,
and split line if statements.
First observation: It seems to me that the formatting of
the code is among the least important things to worry about.
Badly-formatted code is hard to read, yes, but if it's truly
terrible there's no shortage of code reformatters. If you're
happy with the rearrangements reformatters can make, what's
the point of requiring that they be made by humans instead?
Save human effort for the things machines *aren't* good at.

Second observation: I once shared your view that because
the compiler has to inspect the code anyhow, the compiler is
the logical "pinch point" at which to ensure good practice.
But fifteen or twenty years ago I changed my mind: the job
of the compiler is to translate the source code, not to
enforce some organization's standards. Different standards
apply in different organizations -- even in different projects
within the same organization -- so the compiler's suite of
standards would need to be localizable, which adds to the
complexity of the compiler. It's bad enough dealing with
optimizer bugs; do you also want to handle enforcer bugs?
How much time do you want to spend debugging the scripts
or whatever that describe the local style(s)?

Software engineering is a social activity (yes, even
for the so-called "loners"), and making sure that it is
done well and/or according to standards is a social issue.
Technology influences social issues, but is seldom in and
of itself a cure for social ills.

--
Er*********@sun .com
Oct 10 '07 #6
Eric Sosman wrote:
David Mathog wrote:
.... snip ...
>
>Here is an example of the type of style variant I would love to
be able to flag.

if(some_conditi on)
do_something();

The lack of {} around the conditional code very often leads to
errors during code maintenance, [...]

Aside: This assertion is "very often" made, but is it backed by
measurement? I've been omitting braces from one- line consequents
of `if' and `for' and `while' for more than three decades, and
can't recall coming to grief as a result.
My personal rule is that an if controlling a one liner can be
written as a one liner. I.e. in my world:

if (whatever()) something();
and
if (whatever()) {
foo();
something();
}

are both quite legitimate. Note I do not require 0 comparison in
the conditional.
--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Oct 11 '07 #7
David Mathog wrote:
>
.... snip ...
>
Here's Hello World with all "extra" spaces and EOL's removed.
It's down to just 3 lines and two spaces: one between "int" and
"main" and one between "Hello" and "world". My news client
wrapped this after the second space but in the original it was
only a 3 line program.

#include <stdlib.h>
#include <stdio.h>
int main(void){(voi d)fprintf(stdou t,"Hello
world\n");(void )exit(EXIT_SUCC ESS);}

This 3 line form is legal but it's also really hard to read. It
would be nice if gcc (for instance) had at least an optional
-Whuman, to issue warnings for difficult to read but otherwise
legal constructs.
How about:

#include <stdio.h>
int main(void){puts ("Hello World);return 0;}

and, if you really insist, you can (void)puts. Expanding to
minimum readability yields:

#include <stdio.h>
int main(void) {
puts("Hello World);
return 0;
}

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Oct 11 '07 #8
David Mathog wrote:
>
.... snip ...
>
and another may demand:

if(some_conditi on) {
if(something_el se) {
}
}
else {
}

It would be incredibly useful for me in these situations to be able
to throw a compiler switch to check for variation from these styles.
The compiler is clearly a good place to do this since it has to
parse the code thoroughly anyway, and could easily add a few more
rules during that parsing to pick up on things like indent levels,
bracket spacing, and split line if statements.
How about:

if (!some_conditio n) {
/* whatever */
}
else if (something_else ) {
/* whatever else */
}

which I consider clearer.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Oct 11 '07 #9
Eric Sosman wrote:
David Mathog wrote On 10/10/07 12:12,:
>Here is an example of the type of style variant I would love to be able
to flag.

if(some_conditi on)
do_something();

The lack of {} around the conditional code very often leads to errors
during code maintenance, [...]

Aside: This assertion is "very often" made, but is it
backed by measurement? I've been omitting braces from one-
line consequents of `if' and `for' and `while' for more
than three decades, and can't recall coming to grief as a
result.
Measurement no, experience yes. I've seen bugs like this in other
people's code (not mine - I never uses this construct).
This one seems to be relatively common:

if(test)
do_1();
do_2();

I also recall seeing this once:

if(test)
do_1(); do_2();

In both cases resulting in subtle bugs where the code needed do_2() to
be conditional on test, whereas it actually ran unconditionally .
Beginner errors, yes, but once they are in the code, if the resulting
dysfunction isn't huge they can persist a long time.

So far I've not encountered this variant:

if(test)do(1); do_2();
Regards,

David Mathog
Oct 11 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
697
by: Bhushit Joshipura | last post by:
This post contains one question and one proposal. A. May I know why order of evaluation of arguments is not specified in C/C++? I asked a question in comp.lang.c++ for the following possibility and because the languages do not specify the order of evaluation, doing so was an error. int B::f ( int i, int j = i + 1 ) { // j defaults to i + 1
5
2574
by: Derek | last post by:
I came upon the idea of writting a logging class that uses a Python-ish syntax that's easy on the eyes (IMO): int x = 1; double y = 2.5; std::string z = "result"; debug = "Results:", x, y, z; The above example outputs:
1
1632
by: Bob Hairgrove | last post by:
Why can I do this: template<typename A, typename B=A> struct X { /*...*/ }; whereas this gives me an error about an undeclared identifier with MSVC++ 7.1: struct A { A(int arg1, int arg2=arg1); };
13
2670
by: Richard | last post by:
Boy, I'll sure bet this is a FAQ. Many years ago, my "runtime behavior of programming languages" prof absolutely guaranteed that C parameters are evaluated left-to-right. He was a bright guy from CMU whose research focus was on programming languages, and I believed him, but now I'm not so sure. Little help?
4
2578
by: Frank Wallingford | last post by:
Note: For those with instant reactions, this is NOT the common "why is i = i++ not defined?" question. Please read on. I came across an interesting question when talking with my colleagues. According to the standard, most operators evaluate their operands in an unspecified order. This means that in code like this: f() + g()
3
2813
by: andreas ames | last post by:
Hi all, recently I came across a line of code like the following: if seq.erase(seq.begin(), seq.end()) != seq.end() /* ... */ It made me wonder if this is just bogus or if it even can invoke undefined behaviour.
15
1971
by: Jeroen | last post by:
Hi all, I've got a very specific question about the evaluation order in C++. Assume some kind of custom array class, with an overloaded subscript operator. In the following code: { my_array a, b, c; a = b + c;
25
1588
by: mdh | last post by:
Given the expression: while (isaspace(c = *s++)) x+1; (s is an array) Does the increment to 's' occur after "x+1" is evaluated, or after the content of s is assigned to c? Is there a general rule as to when this type of increment occurs? ( I understand that the increment in "c = ++*s" occurs immediately before assignment, so my guess is the same
32
3327
by: silpau | last post by:
hi, i am a bit confused on expression evaluation order in expressions involving unary increment.decrement operators along with binary operators. For example in the following expression x += i + j + k++;
54
3944
by: Rasjid | last post by:
Hello, I have just joined and this is my first post. I have never been able to resolve the issue of order of evaluation in C/C++ and the related issue of precedence of operators, use of parentheses. 1) "The order of evaluation of subexpressions is determined by the precedence and grouping of operators."
0
9628
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9464
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10289
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10061
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8952
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5367
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5493
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3622
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.