-1

I am using the increment operator in prefix n postfix in C++, but i m getting incorrect results, can anyone please guide me n tell me what i m doing wrong :) Thank you :) here is my code :)

 #include <iostream>
 using namespace std;
 int main()
 {
 int a=0;
 cout<<a++<<endl<<++a<<endl;
 }

Expecting Result

 0
 2

but i m getting Result

 1 
 2
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
Romeo
  • 57
  • 8
  • `a++` increments `a` and returns copy of it's value, which is 1. Nothing unexpected here. – Jaa-c Mar 26 '17 at 12:02
  • Both uses are within one statement. You are assuming some kind of left-to-right order which is not correct. – stark Mar 26 '17 at 12:03
  • @Jaa-c It returns copy of value before incrementing, which is (should be?) zero. – Kamil Koczurek Mar 26 '17 at 12:04
  • thank you Christian Hackl, Jaa-c, stark – Romeo Mar 26 '17 at 12:06
  • 1
    It's incredibly easy to run into undefined behaviour if you use `++` on the same object twice within the same expression. Even if the behaviour is well-defined, you still risk confusing yourself and future readers of your code. Do yourself a favour and split the expression: `std::cout << a++ << '\n'; std::cout << ++a << '\n';` – Christian Hackl Mar 26 '17 at 12:14
  • This is well-defined in C++17. – chris Mar 26 '17 at 12:15

1 Answers1

0

This has to do with the increment operator++ and how it functions, depending if you use it as prefix or a postfix:

 #include <iostream>

 int main() {
    int a = 0;
    std::cout  <<  a++  << std::endl 
    // Output: 0. ++ as posfix creates an incremented copy of "a" and AFTER the line gets executed.
    std::cout  <<  ++a  << std::endl; 
    // Output: 1. ++ as prefix creates a copy of "a", an incremented copy BEFORE the line gets executed. 

    std::cout << a++ << std::endl << ++a << std::endl;
    // Output: 0
    //         1. 
    // "a" get incremented only by the prefix operator++
 }

Note: changed using namespace std and I recommend you use namespace+scope operator, like std:: for C++ Standard Library containers.

Community
  • 1
  • 1
Santiago Varela
  • 2,199
  • 16
  • 22