什么是强类型语言
强类型语言: 强类型语言是指我们在定义数据类型时需要指定类型,机器在编译时或运行时可以知晓。
强类型语言可以分为两类:
- 静态类型语言
- 动态类型语言
静态类型语言: 静态类型语言如C、C++、Java等,在这种类型的语言中,变量的数据类型是在编译时就已知的,这意味着程序员在声明变量时必须指定变量的数据类型。我们还需要预定义函数的返回类型以及它所接受的变量的类型。
语法:
data_type variable_name;
示例: 下面的示例说明了展示C++是静态类型语言的代码:
C++
#include <iostream>
#include <string>
using namespace std;
int number(int n){
return n;
}
int main() {
// Here every variable is defined by
// specifying data type to it
string str = "GeeksforGeeks";
int num = 109;
float flo = 12.99;
cout << "I'm a string with value: " << str;
cout << "I'm a number with value: " << number(num);
cout << "I'm a floating point number with value: " << flo;
return 0;
}
输出:
I'm a string with value: GeeksforGeeks
I'm a number with value: 109
I'm a floating point number with value: 12.99
示例2:
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
// Here every variable is defined
// by specifying data type to it
string str="GeeksforGeeks";
int num = 109;
float flo = 12.99;
int num2 = "Welcome to GeekdforGeeks";
cout << "I'm a string with value: " << str;
cout << "I'm a number with value: " << num;
cout << "I'm a floating point number with value: " << flo;
cout << "I'm a number with value: " << num2;
return 0;
}
输出: 它会显示一个错误,因为我们不能直接将值分配给除其定义的数据类型之外的变量:
prog.cpp: In function ‘int main()’:
prog.cpp:11:13: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
int num2="Welcome to GeekdforGeeks";
^
动态类型语言: 这些语言不需要为任何变量预定义数据类型,因为它是由机器在运行时解释的。在这些语言中,解释器根据变量的值在运行时为变量分配数据类型。在这些语言中,我们甚至不需要指定函数返回或接受的变量类型。 JavaScript、Python、Ruby、Perl 等都是动态类型语言的示例。
示例: 这个示例展示了JavaScript作为动态类型语言的特点:
HTML
<script>
var str = "GeeksforGeeks";
var num = 5;
var flo = 12.99;
var num2 = "Welcome to GFG";
function number(n) {
return n;
}
console.log("I'm a string with value: " + str);
console.log("I'm a number with value: " + number(num));
console.log("I'm a floating point number with value: " + flo);
console.log("I'm a string with value: " + num2);
</script>
输出:

极客教程