Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the string type a scalar, and if so why?

Tags:

c++

c

string

scalar

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.

like image 224
SharpHawk Avatar asked Dec 17 '22 01:12

SharpHawk


2 Answers

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)

like image 121
fredoverflow Avatar answered Jan 14 '23 10:01

fredoverflow


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.

like image 30
japreiss Avatar answered Jan 14 '23 09:01

japreiss