Reputation: 27
This is a rather simple question I believe, I simply want to know how to write this more efficiently; I have a pHandle to a process that works fine. However, when I was writing out my error check I realized that if I write
if (pHandle == NULL || INVALID_HANDLE_VALUE)
It will always be true even if the pHandle is valid. I believe this is because INVALID_HANDLE_VALUE will always return true since it's not being checked against anything on the right side. So I wrote it out like this and it started working again.
if (pHandle == NULL || pHandle == INVALID_HANDLE_VALUE)
My question is, how do I write my check to make sure pHandle is not equal to NULL or INVALID_HANDLE_VALUE in an if statement without writing pHandle twice?
Upvotes: 0
Views: 173
Reputation: 211690
The only approach here is to write that out twice. If you want someone to blame, blame C where this restriction is inherited from.
This is largely a product of how C is just "fancy assembler", and in assembly terms your code looks like:
LOAD a, pHandle ;; Load handle into register A
LOAD b, NULL ;; Load NULL into b
CMP a, b ;; Compare a and b
JEQ INNER ;; Test succeeds, so short-circuit to interior "jump if equal"
LOAD b, INVALID_HANDLE_VALUE ;; Load NULL into b
CMP a, b ;; Compare a and b
JNE ENDIF ;; Test fails, so short-circuit exit via "jump not equal"
INNER: ... ;; Interior of if code
ENDIF: ... ;; Outside of if
As there's no CPU instruction for "compare this thing to one or more other things", only a "compare this to that", you're stuck repeating yourself.
The primary reason there's no "compare to multiple" instructions is because a register can hold only one value at a time, there's usually no "array registers", as in can hold an arbitrary list of values. Every operation is defined in terms of one or more registers each holding a single value.
Upvotes: 1