Variable shorthand confusion

Just when I thought I was getting this another confusing issue comes up. LOL Ok so im still in Variables, the book is talking about shorthand operator for adding and subtracting one. The first part says, example: int x=0,x++..........this is supposed to be add one to X, it's return will be 1, then it says, int x=0, cout<<x++; will return a value of 0, its original value because the ++ is after the x therefore it is read after the x. Which is it? I thought I understood till I read this. HELP PLEASE!! thank you

1
2
int x = 0; 
cout << x++; // post-increment 

That returns 0 because it prints out x and then increments it by one.
1
2
int x = 0;
cout << ++x; // pre-increment 

That returns 1 because it increments and then prints it.

Just something to remember when you use them. Post- and Pre- increment/decrement operators.
Last edited on

The book says:" Not only can you us the ++ or -- after a variable, you can also use it in front of the variable --x and ++y. The difference between the two is the value that is returned from the expression, if you write:
int x =0;
cout << x++;
The output is 0. The reason is that even though x is modified, the expression x++ returns the original value of x. Since the ++ appears after the variable, you can think of it being executed after getting the value of the variable. If you put the operation before the variable, you get the new value:
int x+0;
cout<<++x;
Will print 1 because it first adds 1 to x, and then gets the value of x."
This is the exact paragraphs written in the book "jumping into C++". See why im confused?
He was straight about it and gave the common explanation, but he could have used another example to explain it better. If you are still having trouble with it, see if this page helps clear it up any better:
http://www.learncpp.com/cpp-tutorial/33-incrementdecrement-operators-and-side-effects/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>

int& prefix_plus_plus( int& a ) // result is an lvalue (returns reference to a)
{ a = a+1 ; return a ; }

int postfix_plus_plus( int& a ) // result is an rvalue (returns a temporary int)
{ 
    const int value_before_incr = a ;  // value computation
    a = a+1 ; // side effect
    return value_before_incr ; // return computed value
}

int main()
{
    int x ;
    
    x = 5 ; 
    std::cout << ++x << '\n' ; // 6 
    std::cout << x << '\n' ; // 6
    
    // behaves like :
    x = 5 ; 
    std::cout << prefix_plus_plus(x) << '\n' ; // 6 
    std::cout << x << '\n' ; // 6
    
    // behaves like :
    x = 5 ; 
    x = x+1 ;
    std::cout << x << '\n' ; // 6
    std::cout << x << '\n' ; // 6
    
    // -----------------------------------------------
    
    x = 5 ; 
    std::cout << x++ << '\n' ; // 5 (value compuation yields 5)
    std::cout << x << '\n' ; // 6 (side effect has incremented x)
    
    // behaves like :
    x = 5 ; 
    std::cout << postfix_plus_plus(x) << '\n' ; // 5  (value compuation yields 5)
    std::cout << x << '\n' ; // 6 (side effect has incremented x)
    
    // behaves like :
    x = 5 ; 
    const int anonymous_oomputed_value = x ; // value computation yields 5
    x = x+1 ; // side effect increments x
    std::cout << anonymous_oomputed_value << '\n' ; // 5
    std::cout << x << '\n' ; // 6
}

http://coliru.stacked-crooked.com/a/68780d1348fdd378
@JLBorges
That was supposed to be clearer to DianaV than a book designed to teach C++ to beginners? I think something a little simpler would have worked. Something similar to your section of code:
1
2
3
4
5
6
7
8
9
10
11
x++; 
// behaves like
x = 5;
cout << x;  // prints 5
x = x + 1; // x is now 6

++x; 
// behaves like
x = 5; 
x = x + 1;  // becomes 6
cout << x;  // prints 6 

I figured DianaV having 5 posts, and asking about increment/decrement made it fairly obvious she was a beginner and may not know too many things about the language yet. Your code may make less sense to her than the original problem. If I remember right, Jump into C++, at the point it talks about ++/--, the book hasn't even touched on functions, references, or return types.
Holy cow JLBorges!!! Hon Im just learning about what a variable is, I don't know std, const or the rest, I don't even know variables apparently..lol. I can read some of what you wrote. :) Soon I will be able to read it al but not todayl....;) I did notice however that you used the decrement orientation to add the 1 to 5. So what im seeing is that C++ would not actually add one to "C" you would have to write ++C to actually do that or write something like
int a = o
a++;
cout<< a;

would this result in "A" = 1?
How is this a shortcut? I will go to the link to see what that has to say...thanks
> That was supposed to be clearer to DianaV than a book designed to teach C++ to beginners?
> I think something a little simpler would have worked.

It is better than spouting utter non-sense:
BHX Specter wrote:
That returns 0 because it prints out x and then increments it by one.

At least it does not teach wrong things to a beginner.
1
2
3
> int a = o
> a++;
> ...


> would this result in "a" = 1?

Yes.


> How is this a shortcut?

By itself, as a full expression, it is not much of a shortcut. a++ ; or a += 1 ; or a = a+1 ;.

It could be succinct when used as a sub-expression of a bigger expression.
1
2
3
4
int a = 0 ;
// increment a
// print the old value of a before it was incremented
std::cout << a++ ;


@JLBorges
You say it is utter nonsense and that it is teaching wrong things and yet your code says it behaves exactly how I explained it. Would this had been less nonsense? The post-increment operation allows us first to use the value and then to increment it.
Last edited on
Thank you all so very much, honestly I don't know how I could learn this without all of you. I'm only in chapter 4 and the first chapter was setting up the compiler. I'm trying to memorize the terms and totally understand every point this book is trying to teach me so I have a good foundation to build on. I wish there was a work book to go along with this book, with more examples and practice exercises for each individual item I'm trying to learn, would make it so much easier to understand if there were. Does any one know of a work book out there to accompany Jumping into C++?
@DianaV
Unfortunately, no. In all honesty, I wish you had asked here (unless I missed that thread) before you had bought that book because Jumping Into C++ is really nothing more than the author's website tutorials in print. I would have recommended C++ Primer (not to be confused with C++ Primer Plus) or Programming: Principles and Practices Using C++ by Bjarne Stroustrup as beginner books.
Last edited on
> You say it is utter nonsense and that it is teaching wrong things
> and yet your code says it behaves exactly how I explained it.

No it does not. Read the code I posted again.
If you find it too hard to follow the sequence of operations, try to trace it using paper and pencil.

When calling a function (whether or not the function is inline, and whether or not explicit function call syntax is used), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function.
http://en.cppreference.com/w/cpp/language/eval_order


cout << x++; - the full expression
operator<< () - function
x++ - argument expression
increment x - side effect


I would strongly suggest that you learn the basics of C++ first before attempting to teach C++ to others.
Or else you are, albeit unwittingly, harming newbies.

1
2
3
4
5
6
#include <iostream>

void foo( int& x ) 
{
    std::cout << x++ ;
}

> clang++ -std=c++11 -stdlib=libc++ -Wall -Wextra -pedantic-errors main.cpp -c -S && cat main.s
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
.file	"main.cpp"
	.text
	.globl	_Z3fooRi
	.align	16, 0x90
	.type	_Z3fooRi,@function
_Z3fooRi:                               # @_Z3fooRi
	.cfi_startproc
# BB#0:
	pushq	%rbp
.Ltmp2:
	.cfi_def_cfa_offset 16
.Ltmp3:
	.cfi_offset %rbp, -16
	movq	%rsp, %rbp
.Ltmp4:
	.cfi_def_cfa_register %rbp
	subq	$16, %rsp
	leaq	_ZNSt3__14coutE, %rax
	movq	%rdi, -8(%rbp)
	movq	-8(%rbp), %rdi
	movl	(%rdi), %ecx # ***  value computation (value of x before increment)
	movl	%ecx, %edx
	addl	$1, %edx # ***  side effect (increment x)
	movl	%edx, (%rdi) # ***  side effect (store the incremented value into variable x)
	movq	%rax, %rdi
	movl	%ecx, %esi
	callq	_ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEElsEi # *** call the function
	movq	%rax, -16(%rbp)         # 8-byte Spill
	addq	$16, %rsp
	popq	%rbp
	ret
.Ltmp5:
	.size	_Z3fooRi, .Ltmp5-_Z3fooRi
	.cfi_endproc


	.ident	"clang version 3.4 (tags/RELEASE_34/final 206911)"
	.section	".note.GNU-stack","",@progbits

http://coliru.stacked-crooked.com/a/d864ee9184fb66aa


cout << x++; // post-increment

it prints out x and then increments it by one.
It increments x by one and then prints out the old value of x before it was incremented.
(The "as-if" rule holds, of course.)
BHX Specter, thank you I did get the "Programming: Principles and Practices Using C++" by Bjarne Stroustrup book after getting this one, it doesn't line up with this book so I got even more confused. like in Jumping into c++ the include line to get the header file is # include <iostream> in the other book It's:
#include <stdio.h> totally different. I may try to get the other book you suggested and see how closely in line it is to Jumping into C++ . Can you write C++ different ways? I just need to learn and understand the basics right now I'm totally a newbee and I have been able to write simple programs using the information I have learned so far... Like my first and last name using input/output and a grocery list as practice. I also copied the simple calculator in the book and played with it. I can easily read and duplicate that programming and can understand what's happening. So I am learning this. Not to bad for an infant. lol :) Im out of ideas for practicing what I'm learning. It's not that much to date. Your awesome, I can't thank y'all enough for all your help.
@DianaV
The books aren't designed to go hand in hand because every author has their own preferred order to teaching. I would say read Programming: Principles and Practices Using C++ 2nd Edition (it is written by the language creator Bjarne Stroustrup, +1, and is used as the intro course textbook at Texas A&M University, +1) and maybe invest in The C++ Programming Language 4th Edition (also written by Stroustrup) as a reference book for the language.

Alex Allain is a good guy and a good webmaster, but like I pointed out, Jumping into C++ is really nothing more than you paying to get a printed copy of his site's tutorials (which are free to read on his site).
Last edited on
OMG! Thank you all so much I GET IT! you have to complete the operation before asking for its output. I re-read your examples after a little sleep and it totally clicked! Thank you so, so much! I am going to become a programmer, may take some time but that's ok. :) Your all so awesome...im going to look into the other materials you suggested BHX Specter.
One last thing. Looking at your examples I see there are "side effects" I thought that the ++ after the int before computation (incrementing), was ignored or discarded. Looking at some of these examples im seeing that the ++ is maybe held in the buffer and used (executed) in the fallowing computation, when you ask for that value again or something like that? Is that correct?
x = 6 ; std::cout << x++ ;

The observable behaviour is as if the following steps were executed in sequence:

Step 1. Compute the value of the expression x++
(value computation, result_of_the_value_computation is 6, the value of x before it is incremented)

Step 2. Increment the value of x from 6 to 7 (side effect, x = x+1)

Step 3. std::cout << result_of_the_value_computation (print out 6)
I understand your last example JLBorges, thank you for clarifying that point, it totally helped tie up those nasty lose ends I'm going to assume at this point in the learning process that "side effects" are a bad thing so I should avoid them at all costs. :) Till next time my new friends........Thank you all so very much for the help............your all so smart!!!!!!!
Topic archived. No new replies allowed.