Search code examples
c++arrayssizememset

Does C++ memset only works for 0 and -1?


int a[2];
memset(a, 3, sizeof(a)); 

when I run this I am getting output as 0 1. Why not 3 3


Solution

  • Does C++ memset only works for 0 and -1?

    It does work for all byte values.

    int a[2];
    memset(a, 3, sizeof(a)); 
    

    when I run this I am getting output as 0 1.

    I doubt that. Either your system is broken, or you made a mistake.

    Why not 3 3

    Because that's not what std::memset does. It sets every byte to the value that you provide. A multi-byte integer whose each byte have the value 3 doesn't have the value 3. In the value 3, only the least significant byte would have the value 3 and the more significant bytes would be 0.

    Unless you want a repeating byte pattern, std::memset won't be useful to you. If you simply want to assign a value to each element, then you should be using std::fill or its friends:

    std::fill(std::begin(a), std::end(a), 3);
    

    Or just a bare loop:

    for(int& i : a)
        i = 3;
    

    0 happens to be the only byte pattern that preserves the value across all byte widths on all systems; -1 is another but only on 2's complement systems. On 1's complement systems the other pattern has the value -0. This is why std::memset incidentally behaves the same as std::fill when using those values and only when using those values.