Home Backend Development PHP Tutorial 通过静态局部变量看C,C++,C#,Java,PHP的特点

通过静态局部变量看C,C++,C#,Java,PHP的特点

Jun 23, 2016 pm 01:39 PM

0 问题由来

对这个问题的思考来自于面向对象设计中的单例设计模式的实现。

C++中单例模式实现标准代码为:

#include <stdio.h>int init(){    printf("init()\n");    return 22;}int GetTheOnly(){    static int x = init();      return x;}int main(){    int only = GetTheOnly();    return 0;}</stdio.h>
Copy after login

在获取实例函数GetTheOnly()中, 静态局部变量用户存储唯一实例,并且初始化时直接使用init()函数动态初始化。

看起来如此简单,但同样的代码作为C来编译却不能通过,编译器在编译 static int x = init()这一行时报错:

错误:初始值设定元素不是常量

可见,C语言中的静态局部变量初始化时必须以常量赋值,也就是说这个初值必须在编译器就能确定

细想一下,以调用函数来初始化静态变量,C++必须保证init();只运行一次。为达此目的,C++编译器必须增加额外代码,我能想到的C++编译器对于static int x = init(); 可能增加的伪代码如下:

    static int x;    static char flag = 0;    if(flag == 0){        x = init();
Copy after login
        flag = 1;    }    return x;
Copy after login
可见,C++编译器又私底下为我们生成了多余的汇编代码。这样导致的结果就是C++容易使用,却不容易理解。

进而想看看其他几门语言对这个问题的处理,随后使用C#,Java,PHP进行了类似的试验,得出了小小的结论。

1 C#,Java根本就不支持静态局部变量

两者只支持静态成员变量,不支持函数内的静态局部变量。想想也对,静态局部变量几乎总是可以使用静态成员变量来代替。

C#测试代码:

using System;namespace ConsoleApplication2{    class Program    {        static int x = 0;        static int init()        {            Console.WriteLine("init()");            return 22;        }        static int GetTheOnly()        {            // static int x = 0;  static local variable is NOT supported by C#.            if(x == 0)            {                x = init();            }            return x;        }        static void Main(string[] args)        {            GetTheOnly();            GetTheOnly();        }    }}
Copy after login

Java测试代码:

public class t{    public static int init(){        System.out.println("init()\n");        return 22;    }    private static int x = 0;    public static int getTheOnly(){        //static int x = 0;  This line cannot be compiled, static local variable is NOT supported by Java        if(x==0){            x = init();        }        return x;    }    public static void main(String[] args) {        getTheOnly();        getTheOnly();    }}
Copy after login

2 PHP对待静态局部变量与C相同,只支持以常量初始化

PHP测试代码:

<?phpfunction init(){    echo "init()\n";    return 22;}function getTheOnly(){    // static $x = init();  PHP only supports initializing static local vairalbel with constant.    static $x = 0;    if($x==0){        $x = init();    }    return $x;}getTheOnly();getTheOnly();
Copy after login

3 一点思考

通过静态局部变量这一非常小的语言细节,可以发现这几门语言的特点。

C++ 编译器是勤劳全面的全才,尽量为用户提供更多的语言功能,而做到这些必须偷偷为用户生成代码,从而导致C++语言的复杂性和“冰山效应”。(想想C++的多重继承,栈上对象,复制构造。。。)


Java和C#则注重易用性,避免二义性,对于同样功能,只给用户一个正确的选择。(想想单继承、对象只能建立在堆上,垃圾回收)


C则始终保持其简洁高效透明,编译器老实巴交,看到了代码也基本上就能预测到生成的汇编。


PHP的结构化部分模仿C的语法,所以很多特性与之类似,然其毕竟是解释性语言,特别是变量名,类名等本身就可以作为变量的解释性语言特性,让其变得异常灵活。面向对象部分则模仿Java的语法,同时又充分体现了解释语言的特点。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

See all articles