473,395 Members | 1,869 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Unexpected answer, compiler bug?

Hi,

I ran the program below. It should print out 2 but actually it prints
out 1. What's going on? Should I report a bug against the compiler?

Thanks.
void main()
{
int a=1;
a=a++;
printf("%d", a);
}
Dec 25 '07 #1
18 1507
Port Pirie wrote:
Hi,

I ran the program below. It should print out 2 but actually it prints
out 1. What's going on? Should I report a bug against the compiler?

Thanks.
void main()
{
int a=1;
a=a++;
printf("%d", a);
}
You have invoked undefined behaviour thrice. Firstly void main is not
the proper prototype. Proper forms are int main(void) or int main(int,
char**). Secondly you access an object to modify it's value twice
within a sequence point. Thirdly you are calling a variadic function
with no prototype in scope.

Please read the FAQ at the following link:

<http://www.c-faq.com/>
<http://www.clc-wiki.net/>

Dec 25 '07 #2
In article <fk**********@aioe.orgPort Pirie <no***@nospam.invalidwrote:
>I ran the program below. It should print out 2 but actually it prints
out 1. What's going on? Should I report a bug against the compiler?

void main()
{
int a=1;
a=a++;
printf("%d", a);
}
You have asked a variant of Frequently Asked Questions 3.1, 3.2, and 3.3.
See <http://c-faq.com/expr/index.html>. See also questions 11.12a through
11.15 at <http://c-faq.com/ansi/index.html>.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Dec 25 '07 #3
"santosh" <sa*********@gmail.comschrieb im Newsbeitrag
news:fk**********@registered.motzarella.org...
Port Pirie wrote:
>Hi,

I ran the program below. It should print out 2 but actually it prints
out 1. What's going on? Should I report a bug against the compiler?

Thanks.
void main()
{
int a=1;
a=a++;
printf("%d", a);
}

You have invoked undefined behaviour thrice.
Four times actually
Firstly void main is not
the proper prototype. Proper forms are int main(void) or int main(int,
char**). Secondly you access an object to modify it's value twice
within a sequence point. Thirdly you are calling a variadic function
with no prototype in scope.
and fourth you don't end your output with a \n

bye, Jojo
Dec 25 '07 #4
On Dec 25, 12:46 pm, Port Pirie <no...@nospam.invalidwrote:
Hi,

I ran the program below. It should print out 2 but actually it prints
out 1. What's going on? Should I report a bug against the compiler?

Thanks.

void main()
{
int a=1;
a=a++;
printf("%d", a);

}
The key point to your answer is the line:
a=a++;

it evaluates a to 1 in right side, assigns 1 to a in left side, then
increments a used in right side. Use prefix increment instead, like
this:

a = ++a;

Of course, it's advisable you take into account all other advises
about prototype of main() and enting output with \n. :)
Dec 25 '07 #5
On Tue, 25 Dec 2007 14:07:58 +0100, Joachim Schmitz wrote:
"santosh" <sa*********@gmail.comschrieb im Newsbeitrag
>[...]
You have invoked undefined behaviour thrice.
Four times actually
[...]
and fourth you don't end your output with a \n
Whether that is required is implementation-defined. When it's not
required, and your program don't provide one, your program is slightly
less portable, but still has defined behaviour.
Dec 25 '07 #6
On Tue, 25 Dec 2007 05:23:40 -0800, NicoleaSW wrote:
The key point to your answer is the line: a=a++;

it evaluates a to 1 in right side, assigns 1 to a in left side, then
increments a used in right side. Use prefix increment instead, like
this:

a = ++a;
This is exactly as broken as the original code. If you want to increment
a, write a++, or ++a, or a += 1, or a = a + 1, or any other alternative
that you can think of that updates a _once_. Even if it were valid C,
there is no point in saying you want to update a, and then store the
result in a. Updating a already stores the result in a. Trying to store
it again makes no sense.
Dec 25 '07 #7
Port Pirie wrote:
Hi,

I ran the program below. It should print out 2 but actually it prints
out 1. What's going on? Should I report a bug against the compiler?
Your code (below) contains at least three errors (four under the old C89
standard). It cannot reasonably be expected to have any particular
behavior. However, if you wanted to guess what the behavior might be of
this incredibly error-laden code, consider this code block:

{
int a = 1;
int c;
c = a++; /* a++ has the value 1, that value is assigned to c */
}

Does that give you a hint?
If you do not understand why a++ has the value 1, open any elementary C
text and read the very first page in which the post-increment operator
++ is introduced.
void main()
{
int a=1;
a=a++;
printf("%d", a);
}
Dec 25 '07 #8
Ni*******@gmail.com wrote:
The key point to your answer is the line:
a=a++;

it evaluates a to 1 in right side, assigns 1 to a in left side, then
increments a used in right side.
You might think so, but you would be horribly wrong.
This line has completely undefinied behavior.
Use prefix increment instead, like
this:

a = ++a;
You might think so, but you would be horribly wrong.
This line has completely undefinied behavior.
Of course, it's advisable you take into account all other advises
about prototype of main() and enting output with \n. :)
Of course, it's advisable for you to learn about sequence points before
posting "advice".
Dec 25 '07 #9
Ni*******@gmail.com wrote:
On Dec 25, 12:46 pm, Port Pirie <no...@nospam.invalidwrote:
>Hi,

I ran the program below. It should print out 2 but actually it prints
out 1. What's going on? Should I report a bug against the compiler?

Thanks.

void main()
{
int a=1;
a=a++;
printf("%d", a);

}

The key point to your answer is the line:
a=a++;

it evaluates a to 1 in right side, assigns 1 to a in left side, then
increments a used in right side.
Wherever you learned that from, reconsider its educational value;
it's wrong. It's a /permitted/ implementation, but only because
the expression `a = a++` has /no/ defined behaviour -- anything
and everything is permitted.

There are specific words in the Standard that, amongst other things,
make undefined the effects of writing to the same location multiple
times without an intervening "sequence point". Don't Do That.

--
Oh Noes! I Has Meltdownz! Hedgehog
"Life is full of mysteries. Consider this one of them." Sinclair, /Babylon 5/

Dec 25 '07 #10
santosh wrote:
Port Pirie wrote:
>Hi,

I ran the program below. It should print out 2 but actually it prints
out 1. What's going on? Should I report a bug against the compiler?

Thanks.
void main()
{
int a=1;
a=a++;
printf("%d", a);
}

You have invoked undefined behaviour thrice. Firstly void main is not
the proper prototype. Proper forms are int main(void) or int main(int,
char**). Secondly you access an object to modify it's value twice
within a sequence point. Thirdly you are calling a variadic function
with no prototype in scope.

Please read the FAQ at the following link:

<http://www.c-faq.com/>
<http://www.clc-wiki.net/>
Why don't you answer his question? If his complier isn't issuing warnings about
these things he may indeed need to report a bug, just not the one he thinks.

Dec 25 '07 #11
On Wed, 26 Dec 2007 04:37:07 +0000, Chris Torek wrote:
Now, you might argue that the compiler should be able to detect that p
and q both point to b, so that the call to f() should draw a diagnostic.
Though that's tricky if, as Chris notes, the function f() is in a library
that was compiled long long ago on a computer far far away -or worse yet,
is still being written by a co-worker 14,000 miles away in a different
timezone. I'm not aware of any compilers that can diagnose either the
past or the future!
In C, f() can be compiled
separately from the call to f(), and by the time you go to join
the two together (the "link phase"), the information needed is
allowed to have been, and usually has been, discarded.
.... and even if it hasn't, the runtime environment might be presented
with duff user input, eg the user was told to pick two _different_
objects but chose the same one twice. A lot of gets() type bugs come lack
of /programmer/ effort to assist users who enter "ten" instead of "10"...

Remember - if you design an idiot-proof system, the universe will design
a better class of idiot.

Dec 26 '07 #12
On Thu, 27 Dec 2007 20:24:54 -0800, Keith Thompson wrote:
>>>
No, it's not obviously impossible.

I said /all/ behaviour on /all/ platforms.

Yes, I know.
Then you'll understand that its impossible, since no standard can predict
the future.
>What, even the behaviour if I compile naked on a Wednesday?

Why not?
Because there's an infinite set of things that might happen (assuming you
subscribe to non-theistic models of time).
Consider an abstract machine with, say, fixed sizes for all the
predefined types, well-defined behavior on numeric overflow, a fixed
amount of memory with a simple linear addressing scheme, and so forth.
Each implementation must correctly emulate the abstract machine, with no
permitted variations. The language is rigorously tailored to the
abstract machine.
And now we're discussing my /other/ reason why even a standard that
completely defines everything relevant may be such a significant issue as
to render the point moot.

Incidentally, whats your point in debating this with me? Other than to
score points / out-pedant me?
Dec 29 '07 #13
Mark McIntyre <ma**********@spamcop.netwrites:
On Thu, 27 Dec 2007 20:24:54 -0800, Keith Thompson wrote:
>>>No, it's not obviously impossible.

I said /all/ behaviour on /all/ platforms.

Yes, I know.

Then you'll understand that its impossible, since no standard can predict
the future.
Predicting the future is not necessary.
>>What, even the behaviour if I compile naked on a Wednesday?

Why not?

Because there's an infinite set of things that might happen (assuming you
subscribe to non-theistic models of time).
I'm talking about a *finite* abstract machine with a fixed amount of
memory. Such a machine can only have a finite number of states, and
those states can be completely described. A machine language for a
finite machine with no asynchronous actions can be completely
deterministic; there's no reason a higher-level language couldn't do
the same thing.
>Consider an abstract machine with, say, fixed sizes for all the
predefined types, well-defined behavior on numeric overflow, a fixed
amount of memory with a simple linear addressing scheme, and so forth.
Each implementation must correctly emulate the abstract machine, with no
permitted variations. The language is rigorously tailored to the
abstract machine.

And now we're discussing my /other/ reason why even a standard that
completely defines everything relevant may be such a significant issue as
to render the point moot.
Sorry, I don't understand your point here. What other reason?
Incidentally, whats your point in debating this with me? Other than to
score points / out-pedant me?
I'm not trying to score points at all; I'm merely trying to have
technical discussion.

The point is that the fact that C leaves certain things undefined is a
design choice; it's not absolutely necessary for a language definition
to leave *anything* undefined.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
[...]
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 29 '07 #14
Mark McIntyre wrote:
On Thu, 27 Dec 2007 20:24:54 -0800, Keith Thompson wrote:
>>>No, it's not obviously impossible.
I said /all/ behaviour on /all/ platforms.
Yes, I know.

Then you'll understand that its impossible, since no standard can predict
the future.
>>What, even the behaviour if I compile naked on a Wednesday?
Why not?

Because there's an infinite set of things that might happen (assuming you
subscribe to non-theistic models of time).
It doesn't matter. If the description of the behavior doesn't depend
upon your clothing state, then it remains applicable regardless of your
clothing state. If it doesn't depend upon time, then it remains
applicable regardless of the time. Just because there's infinite set of
possibilities to be covered doesn't mean that the description of the
behavior must be infinite too; it needn't even be very large. Defining
that H(x)=2x+3 doesn't require an infinitely long description, despite
the fact that there's an infinite number of different values that x
could have.

Dec 29 '07 #15
On Sat, 29 Dec 2007 12:06:35 -0600, Stephen Sprunk wrote:
"Mark McIntyre" <ma**********@spamcop.netwrote in message
>Because if the cable broke half way along, both halves would be
carrying current and you could get fried off each half.

Wrong. One wire would be carrying current but the other wouldn't -- but
you wouldn't know which.
All I'll say on this is that I know from experience as well as from
training that both live and neutral lines are carrying current. The above
comment is quite correct for an isolated single circuit, but not for a
normal UK housing ring-main with multiple appliances plugged in around
it.
>Even today, most two-wire plugs can be
inserted either way. If it matters to the device, one prong will be
larger than the other
This may be true in the US, but not in the UK.

>
You misunderstand American AC wiring.
This is highly probable. My training is with UK wiring.
For standard 120V circuits,
....
For the 240V outlets
.....

most interesting (seriously). I'll add this to my font of useful info. In
the UK you get three-phase in commericial properties (120degs apart, used
for heavy machinery) but I've never come across 2-phase 180degs.
Dec 29 '07 #16
On Fri, 28 Dec 2007 23:28:30 -0800, Keith Thompson wrote:
Mark McIntyre <ma**********@spamcop.netwrites:
>On Thu, 27 Dec 2007 20:24:54 -0800, Keith Thompson wrote:
>>>>No, it's not obviously impossible.
>>>What, even the behaviour if I compile naked on a Wednesday?

Why not?

Because there's an infinite set of things that might happen (assuming
you subscribe to non-theistic models of time).

I'm talking about a *finite* abstract machine
Note that my original comment was to the effect that no standard can
prescribe *all* behaviours. Not that it cannot prescribe a finite set in
a pre-specified environment.

(Yes, I'm being pedantic here: I realise the OP most likely meant "define
everything relevant to the langauge and its operating envrionment". ).
Sorry, I don't understand your point here. What other reason?
The other one I gave in an earlier post. The one where I noted that if
all behaviours were completely specified there'd be no room for
extensions, and a heck of a lot of platform where it would be uneconomic
or plain impossible to implement the language.
>score points / out-pedant me?

I'm not trying to score points at all; I'm merely trying to have
technical discussion.
I asked because I couldn't see the point of your comments. Sure, for a
pre-defined set of conditions its possible to define everything. That's
tautological.
The point is that the fact that C leaves certain things undefined is a
design choice; it's not absolutely necessary for a language definition
to leave *anything* undefined.
I disagree - inasmuch as I would not want a language standard to specify
a whole host of things, such as my chances getting off with a gorgeous
redhead in Tesco on a Saturday or the score in the next England cricket
match.
Dec 29 '07 #17
Mark McIntyre <ma**********@spamcop.netwrites:
On Fri, 28 Dec 2007 23:28:30 -0800, Keith Thompson wrote:
[...]
I asked because I couldn't see the point of your comments. Sure, for a
pre-defined set of conditions its possible to define everything. That's
tautological.
And that's what I thought we were talking about.
>The point is that the fact that C leaves certain things undefined is a
design choice; it's not absolutely necessary for a language definition
to leave *anything* undefined.

I disagree - inasmuch as I would not want a language standard to specify
a whole host of things, such as my chances getting off with a gorgeous
redhead in Tesco on a Saturday or the score in the next England cricket
match.
I merely meant that a language standard could completely and
rigorously define the syntax and semantics of all programs written in
the language, with no behavior *of a program* left undefined. It
didn't occur to me to consider cricket matches as part of the
discussion.

The C standard leaves the behavior *of some C programs* undefined,
because doing so allows more flexibility for implementers. For each
instance of undefined behavior, we could examine the consequences of
defining it. For example, the standard could define the consequences
of signed integer overflow, at the cost of more expensive arithmetic
even when no overflow occurs. That was a deliberate choice, not a
logical necessity.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
[...]
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 29 '07 #18
(This is all off-topic ... I was going to tack a note on to a
different reply earlier, but am doing it now here.)
>On Sat, 29 Dec 2007 12:06:35 -0600, Stephen Sprunk wrote:
>You misunderstand American AC wiring.
[descriptions snipped]

In article <Rw**************@newsfe3-win.ntli.net>,
Mark McIntyre <ma**********@spamcop.netwrote:
>This is highly probable. My training is with UK wiring.
They are quite different in detail, although the goals are the
same. One particularly important detail is that UK wiring was more
unspecified / ad-hoc quite a bit later than US wiring, which was
standardized to pretty much what we have now back in the 1950s or
so. (That is, the NEC acquired most of today's layout features --
which wires go where and how they are color-coded -- and most states
picked those up as state law back then. Requirements for GFCI and,
now, AFCI are much newer. What I mean is that simple things like
polarized and three-prong outlets were pretty well standardized in
the US by the early 1960s at the latest; this was not the case in
the UK.)
>most interesting (seriously). I'll add this to my font of useful
info. In the UK you get three-phase in commercial properties
(120degs apart, used for heavy machinery) but I've never come across
2-phase 180degs.
We have three-phase here as well, for the same reasons. I have
no doubt this is true there too: it comes in both "delta" and "wye"
configurations. However, the "two phase" (so-called) system for
residential wiring is not actually two phases -- it's just a
220-to-240-volt single phase with a center tap. The voltage from
center to either end is thus approximately 120V (RMS of course;
about 170 volts peak). The center tap is bonded to ground ("earth"
in UK terms) at the house entry, more or less (I think Stephen
mentioned this).

The local distribution is itself three phase (in the US and the UK
and Europe at least, and probably pretty much everywhere). One
phase at a time is tapped / transformed to "house voltages" to feed
residential units (but note that larger apartment complexes usually
get all three phases, and the in-complex distribution then varies).
The US tends to run about two to five houses per phase-tap, while
Europe tends to run about four to seven houses per phase-tap.
(This is mostly because US houses tend to be profligate with energy
use, compared to the UK/Europe. This in turn is mostly because
electric power is surprisingly cheap in the US. No longer quite
so true in California though :-) -- including taxes and such, I
pay about US$.08/kWh in Utah, while my average cost in Calif in
2002 was about $.16/kWh, and marginal rate nearly $.20/kWh.)

One other fun trivia item: most long distance extremely-high-voltage
transmission lines in the US send three-phase AC power. There are
several DC interties, however, for longer distances and to connect
unsynchronized grids (ERCOT in Texas). If you are driving out in
the middle of nowhere and come across a series of transmission
towers, look up at the cable arms. If they come in threes, this
is an AC intertie; if they come in twos, it is a DC intertie.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Dec 29 '07 #19

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

Similar topics

4
by: | last post by:
Some time ago I installed VC# 2003, made a small generic project, compile with the allow unsafe flag and I get the error below: "error CS1577: Assembly generation failed -- Unexpected exception...
2
by: Gerhard Esterhuizen | last post by:
Hi, I am observing unexpected behaviour, in the form of a corrupted class member access, from a simple C++ program that accesses an attribute declared in a virtual base class via a chain of...
10
by: Sean | last post by:
I have a struct that I wrote to test a protocol. The idea I had was to just declare the elements of the struct in the order in which they are sent and received as defined by the protocol. ...
5
by: r.nikhilk | last post by:
Hi, Currently, we are porting C++ applications from 32 bit to 64 bit on AIX platform. (The current version of AIX is 5.3 and xlC verison is 8.0). We are able to compile the applications by...
62
by: ashu | last post by:
hi look at this code include <stdio.h> int main(void) { int i,j=2; i=j++ * ++j * j++; printf("%d %d",i,j); return 0;
8
by: Jim Michaels | last post by:
C:\prj\quiz\withusers>php tareports.php PHP Parse error: syntax error, unexpected T_ELSE in C:\prj\quiz\withusers\tareports.php on line 205 this is the section of code. if (isset($row4)) {...
11
by: Vaibhav87 | last post by:
i write void main() { int j; j - = 0; printf("%d",y); } & i got the answer as 842. i tried it on various computers but the answer is same. pls help me how is this answer is?
13
by: bintom | last post by:
I ran the following simple code in C++ and got unexpected results: float f = 139.4; cout << f; Output: 139.399994;
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.