
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Execution of printf with ++ operators in C
In some problems we can find some printf() statements are containing some lines with ++ operator. In some questions of competitive examinations, we can find these kind of questions to find the output of that code. In this section we will see an example of that kind of question and try to figure out what will be the answer.
Example Code
#include<stdio.h> int main() { volatile int x = 20; printf("%d %d\n", x, x++); x = 20; printf("%d %d\n", x++, x); x = 20; printf("%d %d %d ", x, x++, ++x); return 0; }
Now we will try to guess what will be the output. Most of the compilers takes each parameter of printf() from right to left. So in the first printf() statement, the last parameter is x++, so this will be executed first, it will print 20, after that increase the value from 20 to 21. Now print the second last argument, and show 21. Like that other lines are also calculated in this manner. For ++x, it will increase the value before printing, and for x++, it prints the value at first, then increase the value.
Please check the output to get the better understanding.
Output
21 20 20 20 22 21 21
- Related Articles
- Return values of printf() and scanf() in C
- Measure execution time with high precision in C/C++
- printf(), sprintf() and fprintf() in C
- Format numerical data with printf in Java
- What is the use of `%p` in printf in C?
- Manipulate decimals with numeric operators in C#
- C++ Operators with Precedence and Associativity
- Display localized month name with printf method in Java
- How to use formatting with printf() correctly in Java?
- printf() function in PHP
- Different types of operators in C++
- How to display a SQL execution progress along with execution plan in Oracle?
- Ternary Operators in C/C++
- Unary operators in C/C++
- Compilation and Execution of a C# Program
