473,503 Members | 1,783 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

operator precedance

I am having difficulty understanding this piece of code. I don't
understand why ++*ptr prints 7 and *ptr-- prints an unknown value. I
would have expected it to print 8. I would have to put brackets (*ptr)--
for it work. Thanx in advance.

Joseph

#include <stdio.h>

int main(void)
{
int ctr =6;
int *ptr=&ctr;

++*ptr;
printf("ptr=%d\n", *ptr); /*prints 7*/

*ptr++;
printf("ptr=%d\n", *ptr); /* prints ? */
}

Nov 13 '05 #1
6 2299
Joseph wrote:

I am having difficulty understanding this piece of code. I don't
understand why ++*ptr prints 7 and *ptr-- prints an unknown value. I
would have expected it to print 8. I would have to put brackets (*ptr)--
for it work. Thanx in advance.

#include <stdio.h>

int main(void)
{
int ctr =6;
int *ptr=&ctr;

++*ptr;
printf("ptr=%d\n", *ptr); /*prints 7*/
Right. `++*ptr' is equivalent to `++(*ptr)', which
is equivalent to `++(ctr)', which is equivalent to `++ctr'.
Since `ctr' starts out with the value six, `++ctr' changes
it to seven and yields seven as the value (which is then
discarded). `ptr' itself is not changed, so when you get
to the printf() call `*ptr' is still equivalent to `ctr',
which now has the value seven.
*ptr++;
printf("ptr=%d\n", *ptr); /* prints ? */


Might print anything at all, or nothing, or make demons
fly from your nostrils. Let's go through it: `*ptr++' is
equivalent to `*(ptr++)'. The `ptr++' piece does two things:
it increments `ptr' and yields the value `ptr' had prior to
being incremented. So `*(ptr++)' is equivalent to `(ctr)'
plus the side-effect of incrementing `ptr'. Now when you
get to the printf() call, `ptr' no longer points to `ctr'
because it has been incremented; it points to something "one
slot past the end" of `ctr'. There may or may not actually
be anything at this spot; if something does dwell there it
may or may not be an `int'. You are sticking your hand into
a sack without any idea what's inside: it might be an `int',
or it might be a piece of salt-water taffy, or it might be
an enraged cobra. Don't Do That.

--
Er*********@sun.com
Nov 13 '05 #2
Joseph <ke******@rogers.com> wrote in
news:ec*******************@news02.bloor.is.net.cab le.rogers.com:
I am having difficulty understanding this piece of code. I don't
understand why ++*ptr prints 7 and *ptr-- prints an unknown value. I
would have expected it to print 8. I would have to put brackets (*ptr)--
for it work. Thanx in advance.

Joseph

#include <stdio.h>

int main(void)
{
int ctr =6;
int *ptr=&ctr;

++*ptr;
printf("ptr=%d\n", *ptr); /*prints 7*/

*ptr++;
printf("ptr=%d\n", *ptr); /* prints ? */
}


From:

http://freebsd.ntu.edu.tw/bsd/13/7/21.html

Since they associate right to left, with greedy operator binding we get:

++(*ptr)

or

"increment the dereferenced value of ptr" which is 7.

Next case, same rule we get:

*(ptr++)

or

"increment beyond the address of 'ctr' and then dereference it" which in
this case would be junk.

--
- Mark ->
--
Nov 13 '05 #3
"Mark A. Odell" <no****@embeddedfw.com> wrote in
news:Xn********************************@130.133.1. 4:
From:

http://freebsd.ntu.edu.tw/bsd/13/7/21.html


Oops! Bad table, this is a C++ table but works the same for the operators
we are discussing here.

--
- Mark ->
--
Nov 13 '05 #4
Joseph wrote:
I am having difficulty understanding this piece of code. I don't
understand why ++*ptr prints 7 and *ptr-- prints an unknown value. I
would have expected it to print 8. I would have to put brackets
(*ptr)-- for it work. Thanx in advance.

Joseph
#include <stdio.h>

int main(void)
{
int ctr =6;
int *ptr=&ctr;

++*ptr;
printf("ptr=%d\n", *ptr); /*prints 7*/

*ptr++;
printf("ptr=%d\n", *ptr); /* prints ? */
}
A slightly different table, containing mostly the same information, but also
the direction of associativity.

Operator Precedence and Associativity Rules in C / C++

================================================== ==========================
:: scope resolution (C++, e.g. name::member) left-to-right
:: global (C++, e.g. ::name)
---------------------------------------------------------------------------
-
( ) function call left-to-right
[ ] array element
. class, structure or union member
-> pointer reference to member
:: scope access / resolution (C++)
sizeof size of object in bytes
sizeof size of type in bytes
---------------------------------------------------------------------------
-
++ post increment (lvalue++) right-to-left
++ pre increment (++lvalue)
-- post decrement (lvalue--)
-- pre decrement (--lvalue)
~ bitwise complement
! logical not
- unary minus
+ unary plus
& address of
* contents of
new create object (C++)
delete destroy object (C++)
delete[] destroy array (C++)
(type) cast to type
---------------------------------------------------------------------------
-
.* member pointer (C++) left-to-right
->* pointer reference to member pointer (C++)
---------------------------------------------------------------------------
-
* multiply left-to-right
/ divide
% remainder
---------------------------------------------------------------------------
-
+ add left-to-right
- subtract
---------------------------------------------------------------------------
-
<< bitwise left shift left-to-right bitwise right shift

---------------------------------------------------------------------------
-
< scalar less than left-to-right
<= scalar less than or equal to scalar greater than
= scalar greater than or equal to

---------------------------------------------------------------------------
-
== scalar equal left-to-right
!= scalar not equal
---------------------------------------------------------------------------
-
& bitwise and left-to-right
---------------------------------------------------------------------------
-
^ bitwise exclusive or left-to-right
---------------------------------------------------------------------------
-
| bitwise or left-to-right
---------------------------------------------------------------------------
-
&& logical and left-to-right
---------------------------------------------------------------------------
-
|| logical inclusive or left-to-right
---------------------------------------------------------------------------
-
? : conditional expression right-to-left
---------------------------------------------------------------------------
-
= assignment operator right-to-left
also += -= *= /= %=
&= ^= |= >>= <<=
---------------------------------------------------------------------------
-
, sequential expression left-to-right
---------------------------------------------------------------------------
-

All of the operators in this table can be overloaded (C++) except:

. C++ direct component selector
.* C++ dereference
:: C++ scope access/resolution
?: Conditional

--
Martijn
http://www.sereneconcepts.nl
Nov 13 '05 #5
Mac
On Mon, 29 Sep 2003 19:13:42 +0000, Mark A. Odell wrote:
Joseph <ke******@rogers.com> wrote in
news:ec*******************@news02.bloor.is.net.cab le.rogers.com:
I am having difficulty understanding this piece of code. I don't
understand why ++*ptr prints 7 and *ptr-- prints an unknown value. I
would have expected it to print 8. I would have to put brackets (*ptr)--
for it work. Thanx in advance.

Joseph

#include <stdio.h>

int main(void)
{
int ctr =6;
int *ptr=&ctr;

++*ptr;
printf("ptr=%d\n", *ptr); /*prints 7*/

*ptr++;
printf("ptr=%d\n", *ptr); /* prints ? */
}


From:

http://freebsd.ntu.edu.tw/bsd/13/7/21.html

Since they associate right to left, with greedy operator binding we get:

++(*ptr)

or

"increment the dereferenced value of ptr" which is 7.

Next case, same rule we get:

*(ptr++)

or

"increment beyond the address of 'ctr' and then dereference it" which in
this case would be junk.


Oh, no. that line isn't the problem. The value which is dereferenced in
this line of code is the value ptr held before it was incremented. So, the
value of *(ptr++) is well behaved, and is not by itself illegal, although
it does leave ptr pointing beyond a valid object.

The real problem comes later when ptr, which now points beyond a valid object,
is dereferenced in the printf statement.

Mac
--
Nov 13 '05 #6
"Mac" <fo*@bar.net> wrote in news:pa****************************@bar.net:
Next case, same rule we get:

*(ptr++)

or

"increment beyond the address of 'ctr' and then dereference it" which
in this case would be junk.


Oh, no. that line isn't the problem. The value which is dereferenced in
this line of code is the value ptr held before it was incremented. So,
the value of *(ptr++) is well behaved, and is not by itself illegal,
although it does leave ptr pointing beyond a valid object.

The real problem comes later when ptr, which now points beyond a valid
object, is dereferenced in the printf statement.


Ugh. What was I thinking? Thank you for the correction.

--
- Mark ->
--
Nov 13 '05 #7

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

Similar topics

7
8018
by: Paul Davis | last post by:
I'd like to overload 'comma' to define a concatenation operator for integer-like classes. I've got some first ideas, but I'd appreciate a sanity check. The concatenation operator needs to so...
1
3854
by: joesoap | last post by:
Hi can anybody please tell me what is wrong with my ostream operator??? this is the output i get using the 3 attached files. this is the output after i run assignment2 -joesoap #include...
5
3785
by: Jason | last post by:
Hello. I am trying to learn how operator overloading works so I wrote a simple class to help me practice. I understand the basic opertoar overload like + - / *, but when I try to overload more...
0
1820
by: Martin Magnusson | last post by:
I have defined a number of custom stream buffers with corresponding in and out streams for IO operations in my program, such as IO::output, IO::warning and IO::debug. Now, the debug stream should...
6
4401
by: YUY0x7 | last post by:
Hi, I am having a bit of trouble with a specialization of operator<<. Here goes: class MyStream { }; template <typename T> MyStream& operator<<(MyStream& lhs, T const &)
2
966
by: Boni | last post by:
Dear All, I am wondering that followind produces an exception if Startline is Nothzing. In C++ is first operation is true it would be enougth for the or statement to be true. If ...
5
2272
by: raylopez99 | last post by:
I need an example of a managed overloaded assignment operator for a reference class, so I can equate two classes A1 and A2, say called ARefClass, in this manner: A1=A2;. For some strange reason...
3
3253
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj,...
14
2781
by: Jess | last post by:
Hi, I read about operator overloading and have a question regarding "operator->()". If I have two classes like this: struct A{ void f(); }; struct B{
0
7202
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
7086
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
7280
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
7330
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...
1
6991
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
5578
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,...
0
4672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3167
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...
0
380
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...

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.