Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does memset take an int instead of a char?

Tags:

c

memset

Why does memset take an int as the second argument instead of a char, whereas wmemset takes a wchar_t instead of something like long or long long?

like image 968
user541686 Avatar asked May 07 '11 07:05

user541686


People also ask

Why is the argument type int in all character handling functions?

In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined. "The next biggest type" would actually be short .

Does memset use a loop?

The answer is 'it depends'. memset MAY be more efficient, or it may internally use a for loop. I can't think of a case where memset will be less efficient. In this case, it may turn into a more efficient for loop: your loop iterates 500 times setting a bytes worth of the array to 0 every time.

Why do we need memset?

memset() is used to fill a block of memory with a particular value. The syntax of memset() function is as follows : // ptr ==> Starting address of memory to be filled // x ==> Value to be filled // n ==> Number of bytes to be filled starting // from ptr to be filled void *memset(void *ptr, int x, size_t n);


1 Answers

memset predates (by quite a bit) the addition of function prototypes to C. Without a prototype, you can't pass a char to a function -- when/if you try, it'll be promoted to int when you pass it, and what the function receives is an int.

It's also worth noting that in C, (but not in C++) a character literal like 'a' does not have type char -- it has type int, so what you pass will usually start out as an int anyway. Essentially the only way for it to start as a char and get promoted is if you pass a char variable.

In theory, memset could probably be modified so it receives a char instead of an int, but there's unlikely to be any benefit, and a pretty decent possibility of breaking some old code or other. With an unknown but potentially fairly high cost, and almost no chance of any real benefit, I'd say the chances of it being changed to receive a char fall right on the line between "slim" and "none".

Edit (responding to the comments): The CHAR_BIT least significant bits of the int are used as the value to write to the target.

like image 68
Jerry Coffin Avatar answered Oct 02 '22 17:10

Jerry Coffin