Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮   
     ❯   

C Tutorial

C HOMEC IntroC Get StartedC SyntaxC OutputC CommentsC VariablesC Data TypesC Type ConversionC ConstantsC OperatorsC BooleansC If...ElseC SwitchC While LoopC For LoopC Break/ContinueC ArraysC StringsC User InputC Memory AddressC Pointers

C Functions

C FunctionsC Function ParametersC ScopeC Function DeclarationC Math FunctionsC Inline FunctionsC RecursionC Function Pointers

C Files

C Create FilesC Write To FilesC Read Files

C Structures

C StructuresC Nested StructuresC Structs & PointersC UnionsC typedefC Struct Padding

C Enums

C Enums

C Memory

C Memory Management

C Errors

C ErrorsC DebuggingC NULLC Error HandlingC Input Validation

C More

C DateC Random NumbersC MacrosC Organize CodeC Storage ClassesC Bitwise OperatorsC Fixed-width Integers

C Projects

C Projects

C Reference

C ReferenceC KeywordsC <stdio.h>C <stdlib.h>C <string.h>C <math.h>C <ctype.h>C <time.h>

C Examples

C ExamplesC Real-Life ExamplesC ExercisesC QuizC CompilerC SyllabusC Study PlanC Interview Q&AC Certificate

CVariable Scope


Scope

Now that you understand how functions work, it is important to learn how variables act inside and outside of functions.

In C, variables are only accessible inside the region they are created. This is calledscope.


Local Scope

A variable created inside a function belongs to thelocal scope of that function, and can only be used inside that function:

Example

void myFunction() {
  // Local variable that belongs to myFunction
  int x = 5;

  // Print the variable x
  printf("%d", x);
}

int main() {
  myFunction();
  return 0;
}
Try it Yourself »

Alocal variable cannot be used outside the function it belongs to.

If you try to access it outside the function, an error occurs:

Example

void myFunction() {
  // Local variable that belongs to myFunction
  int x = 5;
}

int main() {
  myFunction();

  // Print the variable x in the main function
  printf("%d", x);
  return 0;
}
Try it Yourself »

Global Scope

A variable created outside of a function, is called aglobal variable and belongs to theglobal scope.

Global variables are available from within any scope, global and local:

Example

A variable created outside of a function is global and can therefore be used by anyone:

// Global variable x
int x = 5;

void myFunction() {
  // We can use x here
  printf("%d", x);
}

int main() {
  myFunction();

  // We can also use x here
  printf("%d", x);
  return 0;
}
Try it Yourself »

Naming Variables

If you operate with the same variable name inside and outside of a function, C will treat them as two separate variables; One available in the global scope (outside the function) and one available in the local scope (inside the function):

Example

The function will print the localx, and then the code will print the globalx:

// Global variable x
int x = 5;

void myFunction() {
  // Local variable with the same name as the global variable (x)
  int x = 22;
  printf("%d\n", x); // Refers to the local variable x
}

int main() {
  myFunction();

  printf("%d\n", x); // Refers to the global variable x
  return 0;
}
Try it Yourself »

However, you should avoid using the same variable name for both globally and locally variables as it can lead to errors and confusion.

In general, you should be careful with global variables, since they can be accessed and modified from any function:

Example

Change the value ofx frommyFunction:

// Global variable
int x = 5;

void myFunction() {
  printf("%d\n", ++x); // Increment the value of x by 1 and print it
}

int main() {
  myFunction();

  printf("%d\n", x); // Print the global variable x
  return 0;
}

// The value of x is now 6 (no longer 5)
Try it Yourself »

Conclusion

To sum up, use local variables (with good variable names) as much as you can. This will make your code easier to maintain and better to understand. However, you may find global variables when working on existing C programs or while collaborating with others. Therefore, it is good to understand how the scope works and how to use it effectively to make sure your code is clear and functional.





×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp