Why do you have to specify the data type when declaring variables

programming-languages

In most coding languages (if not all) you need to declare variables. For example in C# if its a number field then

int PhoneNumber

If I'm using normal English language I do not need to declare PhoneNumber as int to use it. For example if I ask my friend Sam to give me his phone number I say:

"Sam give me the phonenumber"

I wouldn't say

"Char(20) Sam give me the int phoneNumber"

Why do we have to specify data type at all?

Best Answer

In most coding languages (if not all) you need to declare variables.

[…]

Why do we have to specify data type at all?

Those are two independent questions:

  • Why do we need to declare variables?
  • Why do we need to declare types?

Incidentally, the answer to both is: we don't.

There are plenty of statically typed programming languages where you don't need to declare types. The compiler can infer the types from the surrounding context and the usage.

For example, in Scala you can say

val age: Int = 23

or you could just say

val age = 23

The two are exactly equivalent: the compiler will infer the type to be Int from the initialization expression 23.

Likewise, in C♯, you can say either of these, and they both mean the exact same thing:

int age = 23;
var age = 23;

This feature is called type inference, and many languages besides Scala and C♯ have it: Haskell, Kotlin, Ceylon, ML, F♯, C++, you name it. Even Java has limited forms of type inference.

In dynamically typed programming languages, variables don't even have types. Types only exist dynamically at runtime, not statically. Only values and expressions have types and only at runtime, variables don't have types.

E.g. in ECMAScript:

const age = 23;
let age = 23;

And lastly, in a lot of languages, you don't even need to declare variables at all. e.g. in Ruby:

age = 23

In fact, that last example is valid in a number of programming languages. The exact same line of code would also work in Python, for example.

So,

  • even in statically typed languages where variables have types, you don't necessarily have to declare them,
  • in dynamically typed languages, variables don't have types, so obviously you can't even declare them,
  • in many languages, you don't even have to declare variables
Related Topic