概念
强弱类型(Strong and weak typing)表示在程序设计中,经常把编程语言的类型系统分为强类型(英语:strongly typed)和弱类型(英语:weakly typed (loosely typed))两种。
这两个术语并没有非常明确的定义,主要用以描述编程语言对于混入不同数据类型的值进行运算时的处理方式。
特点:强类型的语言遇到函数引数类型和实际调用类型不匹配的情况经常会直接出错或者编译失败;而弱类型的语言常常会实行隐式转换,或者产生难以意料的结果。
编程语言专家Benjamin C. Pierce,《Types and Programming Languages》和《Advanced Topics in Types and Programming Languages》的作者,曾说:“我花了几个星期…试着弄清楚“强类型”、“静态类型”、“安全”等术语,但我发现这异常的困难…这些术语的用法不尽相同,所以也就近乎无用。”
大致而言,“强类型”隐含着编程语言对容许混合情况出现加上了严格的限制,以避免代码以无效的数据使用方式编译或运行。例如,整数除法运算不可用于字符串;链表上的运算步骤不可用于数字。然而,这些限制的本质和效力是极易改变的。
Strong-typing vs Weak-typing
Weak typing is where a language allows you to treat blocks of memory defined as one type as another (casting). Languages like C and C++, although statically typed, are weakly typed.
弱类型是指语言允许将定义为一种类型的内存块视为另一种类型(强制转换)。像C和c++这样的语言虽然是静态类型的,但却是弱类型的。
Languages like Perl and PHP are weakly typed because you can do things like adding numbers to strings and the language will do an implicit coercion for you.
像Perl和PHP这样的语言是弱类型的,因为您可以做一些事情,比如向字符串中添加数字,并且该语言将为您执行隐式强制。
Languages like Java, C# and Python are strongly typed - there is no way you can add a number to a string without doing an explicit conversion.
像Java、c#和Python这样的语言都是强类型的——在不进行显式转换的情况下,不可能向字符串中添加数字。
In addition, there are many large systems that have been created with dynamic type systems. Catching type errors (typos) at compile time only catches a very small proportion of errors and a strong testing strategy produces much more reliable systems irrespective of the type system in use.
此外,还有许多使用动态类型系统创建的大型系统。在编译时捕获类型错误(typos)只能捕获很小比例的错误,而强大的测试策略会产生更可靠的系统,而不管所使用的类型系统是什么。
Strong type is checking the types of variables at compile time. weak typing is checking the types of the system at run-time. For scripts & quick stuff we'll use weak typing, In big programs, strong typing can reduce errors at compile time.
强类型语言在编译阶段检查变量类型;弱类型语言在运行阶段检查变量类型。
静态语言在编译时检查变量类型,动态语言在运行时检查变量类型。
举例
strong type language specication requires its typing rules strongly (i.e. more or less allowing only those automatic type conversions which do not lose information), one can refer to the process as strongly typed, if not, as weakly typed.
Example in c language:
int a;
float b, c;
b=2.2;
c=3.3;
a=b+c;// here we are losing data result is 5 instead of 5.5 because a is an integer
cout<
here ouptput 5.
if language do not allow to automatic type conversion then it should be strongly type otherwise it is weakly typed.
动态类型: if compiler know information about the type of variable or data at run time then it is called dynamic type.
静态类型: if complier get information about type of variable or data at compile time then it is called static type.
总结
尽管如此,使用哪种语言还是要按需而定。个人观点是,编写简单小应用,使用弱类型语言可节省很多代码量,有更高的开发效率。而对于构建大型项目,使用强类型语言可能会比使用弱类型更加规范可靠。