Document Class for Applying Scope

Applying Scope You have seen in some of the examples that you can create a variable inside a method. The variable comes into existence at the point where a statement defines it, and subsequent statements in the same method can then use the variable. | Applying Scope You have seen in some of the examples that you can create a variable inside a method. The variable comes into existence at the point where a statement defines it and subsequent statements in the same method can then use the variable. In other words a variable can be used only after it has been created. After the method has finished the variable disappears completely. If a variable can be used at a particular location in a program the variable is said to be in scope at that location. To put it another way the scope of a variable is simply the region of the program in which that variable is usable. Scope applies to methods as well as variables. The scope of an identifier of a variable or method is linked to the location of the declaration that introduces the identifier into the program as you ll now learn. Defining Local Scope The opening and closing curly braces that form the body of a method define a scope. Any variables you declare inside the body of a method are scoped to that method they disappear when the method ends and can be accessed only by code running within that method. These variables are called local variables because they are local to the method in which they are declared they are not in scope in any other method. This arrangement means that you cannot use local variables to share information between methods. Consider this example class Example void firstMethod int myVar . void anotherMethod myVar 42 error - variable not in scope . This code would fail to compile because anotherMethod is trying to use the variable myVar which is not in scope. The variable myVar is available only to statements in firstMethod. Defining Class Scope The opening and closing curly braces that form the body of a class also create a scope. Any variables you declare inside the body of a class but not inside a method are scoped to that class. The proper C name for the variables defined by a class is fields. Unlike local variables you can use fields to share .

Bấm vào đây để xem trước nội dung
TÀI LIỆU LIÊN QUAN
5    176    1
5    255    1
5    106    0
5    121    1
6    103    1
6    107    1
6    121    1
6    103    0
6    140    0
TÀI LIỆU MỚI ĐĂNG
7    70    1    29-04-2024
2    109    3    29-04-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.