search
HomeBackend DevelopmentC#.Net TutorialCan variables with the same name be used in different functions?

can use. The variables described in the function in C language are local variables, which only work within the function and will not affect other functions. Using the same variable name in different functions does not mean they are the same variable.

Can variables with the same name be used in different functions?

The operating environment of this tutorial: windows7 system, c99 version, Dell G3 computer.

Variables with the same name can be used in different functions.

Tutorial recommendation: "c language tutorial video"

Variables (local variables) defined inside the function

A variable defined inside a function has its scope limited to the inside of the function and cannot be used outside the function. We call such a variable a local variable (Local Variable). The formal parameters of a function are also local variables and can only be used inside the function.

int f1(int a){
    int b,c;  //a,b,c仅在函数f1()内有效
    return a+b+c;
}
int main(){
    int m,n;  //m,n仅在函数main()内有效
    return 0;
}

A few notes:

1) Variables defined in the main function are also local variables and can only be used in the main function; at the same time, the variables defined in other functions cannot be used in the main function. Variables. The main function is also a function and has equal status with other functions.

2) Formal parameter variables and variables defined in the function body are all local variables. The process of transferring values ​​from actual parameters to formal parameters is also the process of assigning values ​​to local variables.

3) You can use the same variable name in different functions. They represent different data and allocate different memories without interfering with each other or causing confusion.

4) Variables can also be defined in statement blocks, and their scope is limited to the current statement block.

About variable naming

Every piece of runnable C language code contains multiple scopes, even the simplest C language code.

int main(){
    return 0;
}

This is the simplest, runnable C language code. It contains two scopes, one is the local scope inside the main() function, and the other is the global scope outside the main() function. area.

C language stipulates that two variables with the same name cannot appear in the same scope, otherwise a naming conflict will occur; however, variables with the same name are allowed to appear in different scopes, and their scopes are different and will not conflict with each other. This sentence has two meanings:

  • Variables with the same name can appear inside different functions, and different functions have different local scopes;

  • Variables with the same name can appear inside and outside the function. The local scope is inside the function, and the global scope is outside the function.

1) Variables with the same name inside different functions are two completely independent variables. They have no correlation or influence on each other.

#include <stdio.h>

void func_a(){
    int n = 100;
    printf("func_a: n = %d\n", n);
    n = 86;
    printf("func_a: n = %d\n", n);
}

void func_b(){
    int n = 29;
    printf("func_b: n = %d\n", n);
    func_a(); //调用func_a()
    printf("func_b: n = %d\n", n);
}

int main(){
    func_b();
    return 0;
}

Running results:

func_b: n = 29
func_a: n = 100
func_a: n = 86
func_b: n = 29

Both func_a() and func_b() define a variable n internally. In func_b(), the initial value of n is 29. After calling func_a() , the n value is still 29, which shows that the n inside func_b() does not affect the n inside func_a(). These two n's are completely different variables. They "don't know" each other at all. They just have the same name. It's like celebrities matching clothes. There are people named Li Hong in Beijing and Yunnan. It's just a coincidence.

2) When the local variable inside the function has the same name as the global variable outside the function, the global variable will be "shielded" in the local scope of the current function and will no longer have any effect. In other words, local variables are used inside the function, not global variables.

The use of variables follows the principle of proximity. If a variable with the same name is found in the current local scope, it will not be searched in the larger global scope. In addition, you can only look for variables from a small scope to a large scope, but not vice versa, using variables in a smaller scope.

Let’s use a specific example to illustrate:

#include <stdio.h>

int n = 10;  //全局变量

void func1(){
    int n = 20;  //局部变量
    printf("func1 n: %d\n", n);
}

void func2(int n){
    printf("func2 n: %d\n", n);
}

void func3(){
    printf("func3 n: %d\n", n);
}

int main(){
    int n = 30;  //局部变量
    func1();
    func2(n);
    func3();
    printf("main n: %d\n", n);
   
    return 0;
}

Running results:

func1 n: 20
func2 n: 30
func3 n: 10
main n: 30

Although multiple variables n with the same name are defined in the code, their scopes are different. , so there will be no naming conflicts.

The following is an analysis of the output results:

For func1(), the output result is 20. Obviously, the internal n of func1() is used instead of the external n.

When func2() is called, the actual parameter n in main() will be passed to the formal parameter n in func2(). At this time, the value of the formal parameter n becomes 30. The formal parameter n is also a local variable, so it is used.

func3() outputs 10, using global variables. Because there is no local variable n in func3(), the compiler can only look for variable n outside the function, that is, in the global scope.

The printf() statement in main() outputs 30, indicating that n in main() is used instead of external n.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of Can variables with the same name be used in different functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.