50 likes | 144 Views
Variables and Function. CS 10061 Introduction to Computer Programming. Variables and Functions. If two functions have a variable named limit, is there a single variable that they both use? If limit is changed in one function is it changed for the other function? Terminology
E N D
Variables and Function CS 10061 Introduction to Computer Programming
Variables and Functions • If two functions have a variable named limit, is there a single variable that they both use? • If limit is changed in one function is it changed for the other function? • Terminology • Recall, curly braces are used to group statements. • Block : A group of statements within curly braces. • See local_variable.cppbasic_function.cpp
Local Variables • A local variable is a variable declared in a block. • This applies to any block including function bodies, conditional bodies, and loop bodies. • Function parameters are local variables also. • Local variable characteristics: • The variable comes into existence when the declaration is executed. • Initialization: • If there is an initialization the initialization is done every time the variable comes into existence. • If there is NO initialization, the variable will have some random value as its initial value. • When execution leaves the block the variable is discarded and is no longer useable. • A variable declared within a block is only useable within the block it is declared in (and other blocks within that same block). • See local_variable.cpp
Global Variables • A global variable is a variable declared outside of all blocks. • Global variable characteristics: • The variable comes into existence before any statements are executed. • Initialization: • If there is an initialization, the initialization is done once when the variable comes into existence. • If there is NO initialization for numeric variables, the initial value will be 0, for programmer defined types usually some reasonable default value. • Global variables exist for the entire running of the program. • Global variables may be accessed and modified by any function. • Global variable are hard to debug since if they have a wrong value any function could have caused the wrong value. • AVOID GLOBAL VARIABLES. global_variables.cpp
Functions: Examples • basic_function.cpp • time.cpp • rand_vals.cpp • sqrt.cpp • my_sqrt.cpp • output_square_function.cpp • square_function.cpp • local_variable.cpp • global_variables.cpp