Question

A few websites claim that the string type is a scalar. As I understand it, scalars are single-value types, as opposed to array types. But isn't a string essentially an array of chars? So why would it be a scalar?

EDIT: If the answer/explanation differs from C to C++, I'd like explanations to include both languages. I'm adding the C++ tag to this question.

Était-ce utile?

La solution

char* and const char* are scalar types, whereas char[n] and const char[n] are not.

Arithmetic types, enumeration types, pointer types, pointer to member types, std::nullptr_t, and cv-qualified versions of these types are collectively called scalar types. (3.9 Types [basic.types] §9)

Autres conseils

The distinction between scalar and aggregate types is fuzzy. A 32-bit integer is also a container of 32 bits. Even though a string is technically an aggregate of characters, we often manipulate them as we would manipulate scalars. We treat them as immutable, compare them, pass them as arguments, etc. In C the aggregate nature of strings is more apparent, but many other languages including C++ make them feel like scalars.

Other examples of the fuzziness are complex numbers and 3D vectors. They are really made up of several doubles, but numerical programs still allocate them on the stack, pass them by value, overload scalar operators on them, and so on.

Generally, all basic primitive data types are considered scalar.

However, because C++ has a STL which is part of the language, you can consider a string (NOT a char array) to be a scalar type.

in C, there's no such string primitive (because the definition of a string in C is in essence a array of scalar char types) so it all depends how you're looking at it.

In C a string is a data format and not a type. A C string is of type array N+1 of char where N is the length of the string. Array types are not a part of the scalar types but of the aggregate types.

C++ also has a string type which is of a class type but which is not part of the scalar types.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top