Unary operators with pointers
In this article, let’s understand unary operators with pointer variables.
Unary operators in C programming are operators that operate on a single operand, hence the term “unary.” When working with pointer variables, unary operators have specific behaviors that relate to memory addresses and values stored at those addresses. Pointer variables store memory addresses, and these addresses can be manipulated using unary operators.
Here are some common unary operators and their behavior with pointer variables:
Let’s begin by considering a scenario where a pointer variable is defined, initialized to the memory address 0xFFFF0000, and has the type uint32_t*
, as illustrated in Figure 1.
Suppose our intention is to increment the value pointed to by pAddress
by 1. The operation pAddress = pAddress + 1
entails an arithmetic addition.
So, if I try to increment *pAddress
by 1, it gets incremented by 4. Because its type is uint32_t*
. That’s why the final result will be 0xFFFF0004 in this case.
Instead of doing this, you can also use the unary increment operator on the pointer variable like pAddress
++. If you do this, then this also yields the same result. So, the final value of the pAddress
will be the same value. It will not be 0xFFFF0001. When you do increment operation or decrement operation on the pointer variable, the increment or decrement depends upon the pointer type.
There are two takeaways from this article.
- One is you can use the pointer variable as an operand with a unary decrement or unary increment operator.
- And when you do that, the arithmetic. i.e., addition or subtraction depends upon the pointer variable type.
And in the following lecture, let’s discuss relational operators in ‘C’.
Get the Microcontroller Embedded C Programming Full Course on Here.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1