Tuesday, March 31, 2015

Time to C something :-)

One of my friend wanted to know what is function, what is pointer, pass by value, what is pass by reference in C. So, i thought to scribble something in linux to show what it is

Here is a simple code which explains some basic concept
===========
#include <stdio.h>
int add(int a, int b)//pass by value function
{
    return a+b;
}

int addr(int *c,int *d)//pass by reference function
{
    return( *c + *d );
}

int main()
{
    //printf("Hello, World!\n");
    int a,b;
    printf("enter 2 digits");
   
    scanf("%d%d", &a,&b);
    printf("there sum is %d",add(a,b)); //invoking pass by value
   
    int *p; //creating a pointer to variable
    p=&a;
    *p=26;
   
    printf("\nmodified value of a is %d",a);
  
    printf("\n using reference\n");
    printf("%d",addr(&a,&b)); //invoking pass by reference function

    return 0;
}

===========

But somehow, it did not work in linux. "using namespace std" did not help.
So, i thought of some online editor and it eased the job.
Ide One compilation
Modified the add() function to edit the value of a,b to show that does not affect the passed values
however similar thing in addr() affecting value of passed variable(as address of the variable is being passed and not the value of it.


The happiness to see the concepts being understood made me happy as well and scribble down the same scriplet here as well.. 

2 comments:

  1. hey the return type for both are int?? for value its int and for address its int& right? correct me if i m wrong

    ReplyDelete
    Replies
    1. Thanks for the reply :-) The arguments being accepted by a function need not be same as the return type of the function. So, although we are accepting address of a variable in addr() function as int* and working on that address in the function, we need not return the address itself from that function. So, return type int is valid.

      Below is one more code snippet I have given for testing the above concept. In addr function we accept 2 ints but we are returning a char from there.
      =========================
      #include
      char addr(int a, int b)
      {
      int c=a+b;
      return (char)c;
      }


      int main(void) {
      // your code goes here
      int a,b;
      printf("enter any 2 digits whose sum is <255\n");
      scanf("%d%d",&a,&b);
      printf("Unicode char for the digit %c",addr(65,1)) ;
      return 0;
      }
      =============
      Although error handling code is not included in above code, you can test with any digits whose sum is < 255 so that you can get its Unicode character.
      Eg: 65 and 1

      Delete