parameter variable c language

Discussion in 'Programmer's Corner' started by TAKYMOUNIR, Dec 5, 2012.

  1. TAKYMOUNIR

    Thread Starter Active Member

    Jun 23, 2008
    351
    1
    what is the different between local variable and parameter variable and golbal variable in c language
    thanks
     
  2. tshuck

    Well-Known Member

    Oct 18, 2012
    3,531
    675
    I will assume by parameter variable you mean the object passed to a function...

    They all differ in scope, meaning they only exist as long as they are within scope. globals, for instance, have....well, global scope, and as such last the entire length of the program. You can modify them and use them anywhere within your program. locals, on the other hand, only last until the end of the section that they were created in, until '}'. Like the local scoped variable, the parameter of a function exists until the end of the function*.

    *there is, however the possibility you passed a variable by reference, that was defined outside the function call. In this case, you will be operating on the variable whose scope is the same as the function call and will last until the section that called the function has ended.


    This might help you....
    Code ( (Unknown Language)):
    1. #include <stdio.h>
    2.  
    3. void PassByValue(int);
    4. void PassByReference(int*);
    5.  
    6. //this is a global variable
    7. int global1 = 1;
    8.  
    9. void main()
    10. {
    11.     printf("global1 is: %i\r\n",global1);
    12.  
    13.     //this variable has local scope to main()
    14.     //it will cease to exist after main() has ended
    15.     int x = 2;
    16.  
    17.     printf("x is: %i\r\n",x);
    18.  
    19.     PassByValue(x);
    20.  
    21.     printf("x is: %i\r\n",x);
    22.  
    23.     PassByReference(&x);
    24.  
    25.     printf("x is: %i\r\n",x);
    26. }
    27. void PassByValue(int value)
    28. {
    29.     //this will modify the value of the
    30.     //variable passed in
    31.     //value will only contain the value
    32.     //until the function returns
    33.     value = value * 2;
    34. }
    35. void PassByReference(int* reference)
    36. {
    37.     //this will modify the contents of the
    38.     //location pointed to by reference
    39.     //reference will contain the value
    40.     //until the variable it points to
    41.     //no longer exists
    42.     *reference = (*reference) * 2;
    43. }
     
    TAKYMOUNIR likes this.
Loading...