Variables in C++ – Where Variables Decleard

Pages : 7
Views : 1,456

Summary of Contents for Manual

Variables in C++ – Where Variables Decleard

  • Page 1

    VariablesAs you probably know, a variable is a named location in memory that is used to hold avalue that may be modified by the program. All variables must be declared before theycan be used. The general form of a declaration istype variable_list;Here, type must be a valid data type plus any modi...

  • Page 2

    common term, local variable. Local variables may be referenced only by statementsthat are inside the block in which the variables are declared. In other words, localvariables are not known outside their own code block. Remember, a block of codebegins with an opening curly brace and terminates wit...

  • Page 3

    scanf("%d%*c", &t);if(t==1) {char s[80]; /* this is created only uponentry into this block */printf("Enter name:");gets(s);/* do something ... */}}Here, the local variable sis created upon entry into the ifcode block and destroyedupon exit. Furthermore, sis known only wit...

  • Page 4

    j = 20;}However, in C++, this function is perfectly valid because you can define local variablesat any point in your program. (The topic of C++ variable declaration is discussed indepth in Part Two.)Because local variables are created and destroyed with each entry and exit fromthe block in which ...

  • Page 5

    Formal ParametersIf a function is to use arguments, it must declare variables that will accept the valuesof the arguments. These variables are called the formal parameters of the function. Theybehave like any other local variables inside the function. As shown in the followingprogram fragment, th...

  • Page 6

    void func2(void);int main(void){count = 100;func1();return 0;}void func1(void){int temp;temp = count;func2();printf("count is %d", count); /* will print 100 */}void func2(void){int count;for(count=1; count<10; count++)putchar('.');}Look closely at this program. Notice that although n...

  • Page 7

    and unwanted side effects. A major problem in developing large programs is theaccidental changing of a variable's value because it was used elsewhere in the program.This can happen in C/C++ if you use too many global variables in your programs.Chapter 2:Expressions23