data-type variableName [= initialValue] ; |
Examples:
int x; float y = 4.0; |
|
int x = 1; // Global variable void f( ) { int y = 4; // Local variable printf("x = %d, y = %d\n", x, y ); } int main(int argc, char *argv[] ) { int z = 2; // Local variable printf("x = %d, z = %d\n", x, z ); x = 777; // Update the global variable f( ); } |
Output:
x = 1, z = 2 x = 777, y = 4 |
The global variable x can be accessed in main( ) and f( )
The local variable y can only be accessed in f( )
The local variable z can only be accessed in main( )
How to run the program:
|
|
you still need to learn how these variables behave
Relating to Java:
|
This C program:
int x = 1; // Global variable void f( ) { int y = 4; // Local variable printf("x = %d, y = %d\n", x, y ); } int main(int argc, char *argv[] ) { int z = 2; // Local variable printf("x = %d, z = %d\n", x, z ); x = 777; // Update the global variable f( ); } |
is equivalent to the following Java program:
public class variables1 { static int x = 1; // Global variable = class variable // (Only 1 copy of this variable) static void f( ) { int y = 4; // Local variable System.out.printf("x = %d, y = %d\n", x, y ); } static void main(String argv[] ) { int z = 2; // Local variable System.out.printf("x = %d, z = %d\n", x, z ); x = 777; // Update the class (~= global) variable f( ); } } |
|
Question:
|
Answer:
|