logo
  • Home
  • Test & Rank
  • About
  • Training
  • Programming
  • CS
  • IT
  • IS
  • ECE
  • EEE
  • EE
  • Civil
  • Mechanical
  • Chemical
  • Metallurgy
  • Instrumentation
  • Aeronautical
  • Aerospace
  • Biotechnology
  • Mining
  • Marine
  • Agriculture
  • MCA
  • BCA
  • Internship
  • Jobs
  • Contact

C Tutorials

C Tutorials - Concepts & Statements
Escape Sequences
ANSI-C Vs K&R-C
Declaration Vs Definition
Phases of Compilation
Macro Vs Const Declaration
Runtime Stack
Conditional Statements
If Statement with Empty Condition
Dangling Else
Loop Statements
While Vs For Loop
Do-While Vs While Loop
Goto Statement
Storage Classes
Function Storage Class
Linkage and Scope of Variables & Functions

C Tutorials - Operators & Expressions
C Expression
C Expression Vs Statement
Operators
Operator Precedence & Associativity
Assignment Operators
Arithmetic Operators
Logical & Arithmetic Shifts
Bitwise Operators
Relational Operators
Logical Operators
Increment & Decrement Operators
Conditional Operator
Comma Operator
Boolean Value
sizeof Operator
sizeof Operator Side Effects
Cast Operator
Unary Operators
L & R Values
Right Shift of Signed Integer

C Tutorials - Pointers
Word
Pointer Vs. Variable
Datatype by Value
Pointer Memory Allocation
C Pointers - addressof (&) and asterisk (*)
C Pointers - Modular Programming
Pointer Indirection or Dereferencing
Illegal or Un-initiatized Pointer
Pointer Constants
Pointer Compatibility
Const Pointer Vs. Pointer Const
Constant Pointer Vs. Regular Pointer
Addressof Operator & Registers
Null Pointer
Null Pointer Indirection
Pointers & L Values
Pointer Operations
Double Pointer or Pointer-to-Pointer

C Tutorials - Functions
Static Function Parameters
Is Function Necessary
Function Components
Function Arguments
Function Agruments - Actual Vs. Formal
Varargs - Variable Arugments
ADTs & Black Boxes For Functions
Recursion
Recursion Vs. Iteration
Recursion Vs. Iteration Efficiency

C Tutorials - Arrays
Array Vs. Variable
One-Dimentional Array
Array Subscripts
Pointers For Arrays
Array - Pointer Vs. Subscript
a[i] vs. i[a]
Arrays
Pointers vs. Arrays
Arrays as Function Arguments
Array - Static and Automatic Initialization
Incomplete Initialization
Character Array Initialization
Multidimentional Array
Multidimentional Array Storage
Pointer to Array
Multidimensional Arrays as Function Arugments
Array of Pointers
Array Size - sizeof() vs. strlen()

C Tutorials - Character & Strings
Type size_t
NULL Character
Char Vs. String
Char Array Vs. String Literal
sizeof() Vs. strlen()
Restricted vs. Unrestricted String Function
String Search - Basic vs. Advanced
strtok() Function
Program Failure - Errno
Libc Character Function
Memory Functions
Command Line Arguments

C Tutorials - Structures & Unions
Arrays vs. Structures
Structure Declaration
Structure Member Access
Self Referential Structures
Mutually Dependent Structures
Structures
Pointer Arithematic - Struct vs. Arrays
Nested Structures
Structure - Dot vs. Arrow Notation
Structure Padding - Boundary Alignment
Structure - Function Argument & Return
Bit Fields
Unions
Structure vs. Union

C Tutorials - DMA
Compile-Time vs. Run-Time Memory Allocation
Free Memory Pool
Dynamic Memory Allocation
malloc, calloc, free
Common Errors - Dynamic Memory Allocation
Memory Leak
DMA - Memory Allocation

C Tutorials - Structures & Pointers
Linked List
Linked List - Dynamic vs. Static Memory Allocation
Singly Liked List
Ordered vs. Unordered - Singly Linked List
Singly Linked List Operations
Doubly Linked List
Doubly Linked List Operations

C Tutorials - Advanced Pointers
Pointer to Pointer
Declaration by Inference
Function Pointer
Callback Functions
Jump Tables
Command Line Arguments
Command Line Arguments - Processing
String Literals Operations Using Pointers

C Tutorials - Preprocessors
Compiler vs. Preprocessor
Compilation Steps on Linux
C Preprocessor
Preprocessor Directives
#define Directive
Macros
Macros vs. Functions
Undef Directive
if, elif and else Directive
Macro Definition at Command Line
Conditional Compilation
Nested Directives
Include Directive Benefits
File Inclusion
Nested File Inclusion
#error, #pragma and #null Directives
C Preprocessor Directive ##

C Tutorials - File I/O
Program Portability
ANSI C
perror() Function
exit() Function
Standard I/O Libary vs. ANSI
Streams
Text & Binary Streams
EOF, FOPEN_MAX and FILENAME_MAX Constants
I/O on Standard Streams vs. Files
Libc I/O Operations
Streams Open & Close
True Functions and Macros
ungetc() Function
Formatted & Unformatted Line I/O
Binary I/O
Flushing and Seeking Functions
setbuf() Function
Stream Error Functions
Temporary Files
File Manipulation Functions
File Handling Functions

C Tutorials - C Library
Standard C Library
Random Functions
String Conversion Functions
Floating Point Functions
Trigonometric Functions
Hyperbolic Functions
Logarithmic and Exponential Functions
Power Functions
floor(), ceil(), fabs() and fmod() Functions
Date & Time Functions
clock() Function
Time of the Day Functions
Date & Time Conversion Functions
setjmp() and longjmp() Functions
Signals - Sync or Async
Signal Handling & Disposition
Signal Processing
Signal Handlers
Volatile Data - Signals
abort() Function
abs(), labs(), div() and ldiv() Functions
atof() and strtod() Functions
Assert Macro
getenv() Function
system() Function
qsort() & bsearch()
Locale

C Tutorials - Runtime Environment
Assembly Code
Runtime Environment Limits
Function Prologue and Epilogue
Stack Frame
Assembly Code - Locals & Prototypes
Code, Data, Heap and Stack Segements
Register Variable Memory Allocation
Register Variable Use
Stack and Frame Pointers
Stack Frame x86-64
Function Epilogue

« Prev Page
Next Page »

Explain Increment and Decrement Operators in C with Examples

Posted on March 3, 2014 by Manish
This C Tutorial explains Increment and Decrement Operators in C.

Well! ++ and — are two Increment and decrement operators respectively in C. Each operator has two forms and these are prefix and postfix forms. In prefix form, operand comes after the operator while in postfix form operand comes before the operator. For example:

    ++man;  /* prefix form */
    cats++; /* postfix form */
 
    --days;
    nights--;

Notice, there must not be any space between the operand and the operator. Also, ++ and — are Unary operators that is each takes just one operand! Being Unary operators they have very high precedence and are put above the arithmetic operators in the precedence table.

advertisement

How they Work: ++ and — operators work the same except ++ increments its operand while — decrements its operand. ++ operator in either form increments its operand by value of 1. For example:

    ++man;      /* prefix form; increments man by 1 */
    cats++;     /* postfix form; increments cats by 1 */
 
    --days;     /* decrements days by 1*/
    nights--;   /* decrements nights by 1*/

One more example:

/* plus_one.c -- incrementing: prefix and postfix */
#include <stdio.h>
int main(void)
{
    int num1 = 0, num2 = 0;
 
    while (num1 < 5) {
        num1++;
        ++num2;
 
        printf("num1  %d, num2 = %d \n", num1, num2)
    }
    return 0;
}

Running plus_one.c produces this output:

    num1 = 1, num2 = 1
    num1 = 2, num2 = 2
    num1 = 3, num2 = 3
    num1 = 4, num2 = 4
    num1 = 5, num2 = 5

The program counted to five twice and simultaneously. We could get the same results by replacing the two increment statements with this:

advertisement
    num1 = num1 + 1;
    num2 = num2 + 1;

Another example:

    shoe = 3.0;
 
    while (shoe < 18.5) {
        foot = SCALE * size + ADJUST;
        printf("%10.1f %20.2f inches\n", shoe, foot);
        ++shoe;
    }

However, we still haven’t taken full advantage of the increment operator. We can shorten the fragment this way:

    shoe = 2.0;
 
    while (shoe++ < 18.5) {
        foot = SCALE * size + ADJUST;
        printf("%10.1f %20.2f inches\n", shoe, foot);
    }

Second, what’s so good about this approach? It is more compact. More important, it gathers in one place the two processes that control the loop. The primary process is the test: Do you continue or not? In this case, the test is checking to see whether the shoe size is less than 18.5. The secondary process changes an element of the test; in this case, the shoe size is increased.

Suppose you forgot to change the shoe size. Then shoe would always be less than 18.5, and the loop would never end. The computer would churn out line after identical line, caught in a dreaded infinite loop. Eventually, you would lose interest in the output and have to kill the program somehow. Having the loop test and the loop change at one place, instead of at separate locations, helps you to remember to update the loop.

A disadvantage is that combining two operations in a single expression can make the code harder to follow and can make it easier to make counting errors.

advertisement

Another advantage of the increment operator is that it usually produces slightly more efficient machine language code because it is similar to actual machine language instructions.

But there is difference between prefix and postfix increments when an expression contains two or more different terms then they evaluate differently. For example:

    y = a + ++man;  /* prefix form; increments man by 1 */
    y = a + cats++; /* postfix form; increments cats by 1 */
 
    /* 
     * in the first exp. man is incremented by 1 before it is used in
     * the exp. while in the second the value of cats is incremented
     * after it is used in the exp.
     */

How does this happen? Actually, in any exp. with two or more terms, copy of operand, with which ++ operator is associated, is used. In prefix form, operand is first incremented then copy of operand is used in the exp. In postfix form copy of original value of the operand is created and used in the exp. then operand is incremented. For example:

    b = ++i;  /* different result for b if i++ is used */
    ++i;      /* line 1 */
    b = i;    /* same result for b as if i++ used in line 1 */

Precedence of ++ and — operators

The increment and decrement operators have a very high precedence of association; only parentheses are higher. Therefore, x * y++ means (x) * (y++), not (x * y)++, which is fortunate because the latter is invalid. The increment and decrement operators affect a variable (or, more generally, a modifiable lvalue), and the combination x * y is not itself a variable, although its parts are.

Don’t confuse precedence of these two operators with the order of evaluation. Suppose you have the following:

    y = 2;
    n = 3;
 
    nextnum = (y + n++) * 6;

What value does nextnum get? Substituting in values yields

    nextnum = (2 + 3) * 6 = 5 * 6 = 30

Only after n is used is it increased to 4. Precedence tells us that the ++ is attached only to the n, not to y + n. It also tells us when the value of n is used for evaluating the expression, but the nature of the increment operator determines when the value of n is changed.

When n++ is part of an expression, you can think of it as meaning “use n; then increment it.” On the other hand, ++n means “increment n; then use it.”

Another possible source of trouble is a statement like this one:

    ans = num / 2 + 5 * (1 + num++);

Again, the problem is that the compiler may not do things in the same order you have in mind. You would think that it would find num/2 first and then move on, but it might do the last term first, increase num, and use the new value in num/2. There is no guarantee.

Yet another troublesome case is this:

    n = 3;
    y = n++ + n++;

Certainly, n winds up larger by 2 after the statement is executed, but the value for y is ambiguous. A compiler can use the old value of n twice in evaluating y and then increment n twice. This gives y the value 6 and n the value 5, or it can use the old value once, increment n once, use that value for the second n in the expression, and then increment n a second time. This gives y the value 7 and n the value 5. Either choice is allowable. More exactly, the result is undefined, which means the C standard fails to define what the result should be.

Remember how we can easily avoid these problems:
1. Don’t use increment or decrement operators on a variable that is part of more than one argument of a function.
2. Don’t use increment or decrement operators on a variable that appears more than once in an expression.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.
« Prev Page - Explain Logical Operators in C with Examples
» Next Page - Explain Conditional Operator in C with Examples

« Explain Logical Operators in C with Examples
Explain Conditional Operator in C with Examples »
advertisement

Deep Dive @ Sanfoundry:

  1. C# Programming Examples on Mathematics
  2. C++ Programming Examples on Graph Problems & Algorithms
  3. Simple Java Programs
  4. Java Programming Examples on Graph Problems & Algorithms
  5. C Questions and Answers
  6. C Programming Examples on Bitwise Operations
  7. C Programming Examples on Graph Problems & Algorithms
  8. C# Programming Examples on Gaming
  9. C# Basic Programming Examples
  10. C# Programming Examples on Conversions
Manish Bhojasia
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Facebook | Twitter

Best Careers

Developer Tracks
SAN Developer
Linux Kernel Developer
Linux Driver Developer
Linux Network Developer

Live Training Photos
Mentoring
Software Productivity
GDB Assignment
Sanfoundry is No. 1 choice for Deep Hands-ON Trainings in SAN, Linux & C, Kernel Programming. Our Founder has trained employees of almost all Top Companies in India such as VMware, Citrix, Oracle, Motorola, Ericsson, Aricent, HP, Intuit, Microsoft, Cisco, SAP Labs, Siemens, Symantec, Redhat, Chelsio, Cavium, ST-Micro, Samsung, LG-Soft, Wipro, TCS, HCL, IBM, Accenture, HSBC, Mphasis, Tata-Elxsi, Tata VSNL, Mindtree, Cognizant and Startups.

Best Trainings

SAN I - Technology
SAN II - Admin
Linux Fundamentals
Advanced C Training
Linux-C Debugging
System Programming
Network Programming
Linux Threads
Kernel Programming
Kernel Debugging
Linux Device Drivers

Best Reference Books

Computer Science Books
Algorithm & Programming Books
Electronics Engineering Books
Electrical Engineering Books
Chemical Engineering Books
Civil Engineering Books
Mechanical Engineering Books
Industrial Engineering Books
Instrumentation Engg Books
Metallurgical Engineering Books
All Stream Best Books

Questions and Answers

1000 C Questions & Answers
1000 C++ Questions & Answers
1000 C# Questions & Answers
1000 Java Questions & Answers
1000 Linux Questions & Answers
1000 Python Questions
1000 PHP Questions & Answers
1000 Hadoop Questions
Cloud Computing Questions
Computer Science Questions
All Stream Questions & Answers

India Internships

Computer Science Internships
Instrumentation Internships
Electronics Internships
Electrical Internships
Mechanical Internships
Industrial Internships
Systems Internships
Chemical Internships
Civil Internships
IT Internships
All Stream Internships

About Sanfoundry

About Us
Copyright
Terms
Privacy Policy
Jobs
Bangalore Training
Online Training
Developers Track
Mentoring Sessions
Contact Us
Sitemap
© 2011 Sanfoundry. All Rights Reserved.