InsideLoop
InsideLoop

Reputation: 6255

How to get the 0 of a numeric type in C++?

Is there a standard way to get the 0 and the 1 of a numeric type in C++. This is useful when writing linear algebra routines templated with types that could be: int, double, unsigned int, ...

I am thinking of

static_cast<T>(0)

but I am wondering if there is not a better way.

Upvotes: 2

Views: 665

Answers (4)

vz0
vz0

Reputation: 32923

Native data types initialized to a default value are initialized to zero.

int a = int(); // 0
double b = double(); // 0.0
T x = T(); // same as static_cast<T>(0) for T as a native type

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254631

Usually just 0 and 1 will be fine, letting the promotion rules do the right thing.

If you want to be sure that they're converted to the expected type, use T(0) and T(1).

(As other answers point out, you could get the zero value from value-intialisation, T() or T{}. But there's no similar way to get 1; and in my view, little point in (slightly) reducing the clarity just to save a single character.)

Upvotes: 4

5gon12eder
5gon12eder

Reputation: 25439

In C++11 I prefer using T {}. The nice thing is that it works correctly for any default-constructible type.

Upvotes: 1

Codor
Codor

Reputation: 17605

I would use (T)0 what is basically what you already use. If you implement anything near to a linear algebra system, you could consider wrapping all kinds of desired numerical typed in a consistens base class, permitting a more structual representation of fields, rings and the like.

Upvotes: 0

Related Questions