You are here:

C++/pre/post operators

Advertisement


Question
Hi, I just did a simple program trying to show the difference between the use increment and decrement operators before and after the variable, but it wasn't what I want. How can I change this program so that it will show the difference between placing the increment/decrement operators?

#include <iostream>
using namespace std;
int main() {

  int a = 11;

  cout << a++ << " " << ++a << " \n";

  cout << a-- << " " << --a << " \n";

  return 0; }

Answer
Hello, Angela.

Remember that the prefix and postfix operators occur based on the entire line of code, not their position within the line of code.  So, in your sample, the first cout statement would increment a prior to the execution of the line, execute the line, then increment a again.  To better demonstrator what's happening, you need to split the output into multiple statements, such as:

   #include <iostream>
   using namespace std;
   int main()
   {
       int a = 11;
       cout << a << "\n";
       cout << a++ << "\n";
       cout << a << "\n";
       cout << ++a << " \n";
       cout << a << "\n";

       cout << a << "\n";
       cout << a-- << "\n";
       cout << a << "\n";
       cout << --a << " \n";
       cout << a << "\n";

       return 0;
   }

You're welcome, of course, to remove some of the "cout << a" lines, since you will end up with the same value being printed out repeatedly, but I find printing just a prior to and after each operator really helps visualize what is going on.

If you have any further questions, just let me know!

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C++ code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2016 About.com. All rights reserved.