tags:

views:

321

answers:

4

What is the right way to use logical operators with size_t and pid_t types? I mean: is legal to write something like the following?
e.g.:

size_t sz;  
/* some kind of assignment */  
if(sz > 0){  
  /* do something */  
}

e.g.:

void f(pid_t pid,...){  
  if(pid > 0){  
    /* do something */  
  }  
  /* ... */  
}

..or I have to do some cast?

EDIT
ok for answers;
now, considered what has been told, can someone give me a reason for coding that way:

void *my_malloc(size_t size){
  if(size <= 0){
    return NULL;
  }
  /* something else... */
}

My teacher wrote that code.
Does it make sense?
I don't know how many bits are reserved for size_t type(it is implementation-dependent)
but surely it is an unsigned(your answer), so why the above expression?

+5  A: 

Yes, it's legal. Both arguments to > will be promoted to a matching type before the comparison is made.

Be aware that for an unsigned type such as size_t, > 0 means the same as != 0.

Charles Bailey
+1  A: 

size_t and pid_t really are integer values of different flavours -- so yes.

From what I understand, the whole point behind them, indeed, is that the flavour of size_t and pid_t may vary between implementations, OSes and architectures (say, 32 bit v 64 bit) and whatnot.

badp
A: 

In C, size_t is an unsigned type and its size is the size an int type takes on the underlying architecture.

Because C is weakly typed you could however assign signed integers to a size_t type. The responsibility of using the types properly partly rests on the programmer.

In your case since you are comparing the size_t type to zero it is fine. Try comparing it to a negative number. You would be surprised.

ardsrk
A: 

There's no problem in comparing a size_t value with an int value as long as you remember that the int value will be implicitly converted to unsigned type (since size_t is unsigned).

Because of the above, some compilers will issue a warning when you mix signed and unsigned types in comparisons. In that case, in order to suppress the warning you'd have to explicitly convert the signed value to an appropriate unsigned type. However, these compilers don't normally issue any warnings when the signed value is a non-negative compile-time constant, meaning that in your example there's no need to cast an explicit 0 to unsigned type (or use 0U).

AndreyT