In this article I will discuss about the various arithmetic operations in C. Lets discuss them under the following three sub topics -
1. Increment/Decrement And Addition/Subtraction
2. Difference & Comparison
3. Invalid operations
1. Increment/Decrement And Addition/Subtraction
Increment or decrement of a pointer is dependent on the size of the variable on which we are applying the increment/decrement operation.
new value of the pointer = current value (address) + i * size_of(data type)
new value of the pointer = current value (address) - i * size_of(data type)
Behavior with the array
When pointer is pointing to the array and if we increase the pointer then the new value (address) contains would be
New Address of Pointer = Address of Pointer + i*(Size of Data Type)*(Size of Array)
Check the following example
#include<stdio.h>
int main(){
float var[5]={1.01, 2.02, 3.03, 4.04, 5.05};
float(*ptr)[5];
ptr=&var;
printf("Value inside ptr : %u",ptr);
ptr=ptr+1;
printf("Value inside ptr : %u",ptr);
return 0;
}
Sample Output
Value inside ptr : 100 (if)
Value inside ptr : 120
One should always remember that only integer can be added to a pointer variable. But for subtraction we can subtract one pointer from another if they are of same type.
2. Difference & Comparison
Two pointer can be subtracted if they hold same memory space and same type.
ptr2 - ptr1 = (Address of ptr2 - Addres of ptr1) / sizeof(*ptr1 or *ptr2)
Comparison of two pointer is perfectly valid in C even if they hold different type of variable, see the following example
int main()
{
int *ptr1;
float *ptr2;
ptr1 = (int *)1;
ptr2 = (float *)2;
if(ptr2 > ptr1)
printf("Ptr2 is far from ptr1");
return(0);
}
3. Invalid operations
Following operations are invalid operations with pointers
1. Addition of two pointers
2. Multiplication of two pointers/one pointer and one variable(int/float etc)
3. Division between two pointers/One pointer and one variable (int/float etc)
4. Modulo operation on any pointer
5. Any Bitwise operation, negate operation