0

I have read almost every other post about size_t on SO but still i cant get why it should be used. Also i would like to know more about it. I already know that it is unsigned,it cannot be negative,it is used to represent size of the object.

rooni
  • 1,036
  • 3
  • 17
  • 33
  • Syntactically this is a different question. For example size_t should be used to index an array. Unfortunately many programmers will use an int (especially in c99 style for loops) as an index which may have to be sign extended to size_t ... introducing an unnecessary extra instruction and not actually saving any memory (if size_t is 8 bytes and int is 4 bytes for instance) since it most likely ends up in a register anyhow. – technosaurus Oct 16 '17 at 04:02
  • Certain functions (e.g. `malloc`) take arguments of `size_t` as it is large enough to contain valid values (while an `unsigned int` might not be). Same goes for array indexes. – ikegami Oct 16 '17 at 04:07
  • An alternate duplicate [What is size_t in C?](https://stackoverflow.com/questions/2550774/what-is-size-t-in-c) – Bo Persson Oct 16 '17 at 04:08
  • `size_t` is used to represent size of _any_ object. Is the right range (width) to represent that index of _any_ array. It is the Goldilocks type - never to narrow for any object, never needs to be wider for any object to accomplish those goals. `int`, `unsigned`, etc. are not specified to accomplish that. – chux - Reinstate Monica Oct 16 '17 at 05:48
  • @technosaurus on the contrary, a clever C compiler will realize that overflow will have undefined behaviour and just use a 64-bit register instead of the 32-bit one. Unless you care about performance in non-optimized programs, which you shouldn't. – Antti Haapala -- Слава Україні Oct 16 '17 at 07:48
  • @BoPersson changed. Please whoever did that remove the reopen vote. Answer in the duplicate instead. – Antti Haapala -- Слава Україні Oct 16 '17 at 07:50
  • @AnttiHaapala compile the following with `size_t` instead of `int` in your "clever" compiler and see if you change your mind: `size_t mystrlen(const char *s){ int i = 0; while (s[i])++i; return i; }` – technosaurus Oct 16 '17 at 08:14
  • @BoPersson the proposed duplicate is also syntactically different. This asks what is its purpose, not what is it. The same way "what is the purpose of intXX_t?" is different than "what is the typedef for intXX_t?" – technosaurus Oct 16 '17 at 08:20
  • @technosaurus please stop complaining, the question and the answer very much do ask "Should I use int i; or size_t i;?". Also, GCC [compiled the code this without sign extension, using 64-bit registers](https://godbolt.org/g/nyS5MY), happy? – Antti Haapala -- Слава Україні Oct 16 '17 at 08:33

0 Answers0