Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no immutable set of ints while immutable set of chars is possible?

char *str = "Hey baby";

creates memory for the string and points str to it. If this is valid, why not the following:

int *x = {7, 0, 1};

This should do the same, except they are ints instead of chars.

like image 937
tomol Avatar asked Mar 08 '15 06:03

tomol


1 Answers

There is "immutable set of ints", it looks like:

(const int[]){7, 0, 1}

The proper terminology is compound literal. You can point to it:

const int *ptr = (const int[]){7, 0, 1};

For historical reasons, string literals do not have const type despite being immutable. But it is a good idea to use a const char * to point to them so that the compiler will detect when you try to write to one.

Compound literals with const type may be "collapsed" in the same way that string literals can, i.e. they may overlap with other such compound literals. Non-const compound literals do have unique addresses and may be written to.

like image 60
M.M Avatar answered Sep 28 '22 07:09

M.M