0

This code prints different values for ++i||j++&&++k depending on whether the printf function or cout is used. Why is that?

#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{

    int i = 1,j=1,k=1;
    cout<<++i||j++&&++k; 
    printf("%d", ++i||j++ && ++k);

}
dbush
  • 205,898
  • 23
  • 218
  • 273
Azmeer
  • 13
  • 1
  • 6
    Since you'll never, *ever* be writing code like this in a production scenario, you don't need to know the answer to this question. – Robert Harvey Jun 23 '21 at 16:00
  • 2
    This doesn't look undefined behavior like `i++ + ++i` because each variables are used only once per statements. – MikeCAT Jun 23 '21 at 16:01
  • 1
    duplicates: [Why doesn't ++i || ++j && ++k give the expected value](https://stackoverflow.com/q/55517958/995714), https://stackoverflow.com/q/28145152/995714, [How to solve this logical expression?](https://stackoverflow.com/q/33924522/995714), [How to solve this logical expression? (closed)](https://stackoverflow.com/q/33924522/995714) – phuclv Jun 23 '21 at 16:07

1 Answers1

3

According to C++ Operator Precedence - cppreference.com, the << operator has higher precedence than || operator. Therefore, the statement

cout<<++i||j++&&++k;

means

(cout<<++i) || j++&&++k;

Therefore, the value of i after the increment is printed.

In the other hand, the value of ++i||j++ && ++k will be printed by

printf("%d", ++i||j++ && ++k);

Also note that the execution of cout<<++i||j++&&++k; may affect the result of printf("%d", ++i||j++ && ++k); because the ++ operator has side effects and the values of the variables aren't reset between the statements.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70