Wednesday, December 30, 2009

Assign initial value to a pointer

Today I suddenly got an idea. Most of time when we use pointer, we create a variable, and assign initial value to it, and then take its address become the value of a new pointer for succeeding use. But we create a redundant identifier here.

In fact, we could always create a fundamental type pointer and assign initial value to it through dereference operator like this snippet.

and no redundant variable here.

But when we define a simple struct like this.

We should assign initial value through arrow operator like third and fourth line in below snippet. Using brace to assign value as the same as first snippet is wrong syntax.

With a complex struct definition, this way increases many redundant code. Using brace to assignment initial value without creating redundant identifier could be done like this.

But I consider writing (*aPtr) = { 1, 2 }; may be the most intuitive way and it doesn't conflict with other syntax in C.