Pages

Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Jul 10, 2013

Defining Macros

Example 1
#include <stdio.h>

#define SUM a+b    // Macros used just to replace values .
                                        // Whenever compiler see 'SUM' keyword in the program      
                                       //  it will replaced with a+b .

                                       //  It works on the principal of function, so you don't have to
                                       //  write same long particular statement every where in the program 
                             

int main (){

   int a = 5,
       b = 3,
       c;             

   c = SUM - 1;     // this statement is same as c = a + b - 1;
   printf("%d", c);

   return 0;

}

 

Jul 2, 2013

Some addressing fundamentals for C beginners


The following program explains how properly addressed variable don't loose their correct values

#include<iostream>
using namespace std;

void func_widout_address(int a, int b){
a = 10;
b = 30;
}

void func_wid_address(int &x, int &y){
x = 100;
y = 200;
}
int main(){
int a = 20;
int b = 40;

func_widout_address(a,b);
cout<<"a: "<<a<<", b: "<<b<<endl;

func_wid_address(a,b);
cout<<"a: "<<a<<", b: "<<b<<endl;
return 0;
}
// ** Output **
// a: 20, b: 40
// a: 100, b: 200

Passing number of Vairable Arguments in function

Passing number of Variable Arguments in function

#include <stdio.h>
#include <stdarg.h>

int sum(int num, ...); /* Function which takes n number of arguments */

int main(void){
  int s1;
  s1 = sum(4, 100,200,300,400);/* Lets put some numbers to add up       */
  s2 = sum(6,6,6,6,6);        /* which can be changed on each function */
                               /* call, but calling the same function   */
  printf("The sum S1 is: %d\n",s1);
  printf("The sum S2 is: %d\n",s2);
  return 0;
}

int sum(int num,...){
  int S = 0, i;
  va_list L; /* 'va_list' - structure defined in 'stdarg.h' header file */

  va_start(L,num); /* 'va_start' -function taking object 'L'(of Structure 
                       va_list) and 'num' -total number of arguments
                       passed when 'sum' function is called */
                   /*  Object 'L' will hold all the values when sum is   
                       called */

  for(i=0;i<num;i++){
   S += va_arg(L, int); /* va_arg will convert current value is L into
                          'int' (function argument) and return an 'int' */
  }

  va_end(L);        /* destructing Object 'L'  */
return S;           /* returning 'S' to command line */
}