Saturday, 10 August 2013

Variable Arguments in C

Welcome to Wind Trainers :: Trainers, C, Tutorials, Programming, Java, VB.net, C++, ANSI, Learn C, Learn Programming
Forum | Contact

C Tutorials


| Variable Arguments |


Sometime we may come across a situation when you want to have a function which can take variable number of arguments i.e. parameters, instead of predefined number of parameters. The C programming language provides a solution for this situation and we are allowed to define a function which can accept variable number of parameters based on your requirement. The following example shows the definition of such a function.

int func(int, ... )
{
.
.
}
int main()
{
func(1, 2, 3);
func(1, 2, 3, 4);
}

It should be noted that function func() has last argument as ellipses i.e. three dotes (...) and the one just before the ellipses is always an int which will represent total number variable arguments passed. To use such functionality you need to make use of stdarg.h header file which provides functions and macros to implement the functionality of variable arguments and follow the following steps:

Define a function with last parameter as ellipses and the one just before the ellipses is always an int which will represent number of arguments.

Create a va_list type variable in the function definition. This type is defined in stdarg.h header file.

Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file.

Use va_arg macro and va_list variable to access each item in argument list.

Use a macro va_end to clean up the memory assigned to va_list variable.

Now let us follow the above steps and write down a simple function which can take variable number of parameters and returns their average:

#include <stdio.h>
#include <stdarg.h>
double average(int num,...)
{
va_list valist;
double sum = 0.0;
int i;
/* initialize valist for num number of arguments */
va_start(valist, num);
/* access all the arguments assigned to valist */
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int);
}
/* clean memory reserved for valist */
va_end(valist);
return sum/num;
}
int main()
{
printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}

It should be noted that the function average() has been called twice and each time first argument represents the total number of variable arguments being passed. Only ellipses will be used to pass variable number of arguments.

 

Variable in C

Welcome to Wind Trainers :: Trainers, C, Tutorials, Programming, Java, VB.net, C++, ANSI, Learn C, Learn Programming
Forum | Contact

C Tutorials


| Variable |

A variable is named location in memory. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in previous chapter, there will be following basic variable types:

Type Description
char Integer type, Single byte of storage
int Natural size of the integer for the machine usually 2 bytes
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.

 


| Variable Declaration |

All variables must be declared before we use them in C program, although certain declarations can be made implicitly by content. A declaration specifies a type, and contains a list of one or more variables of that type as follows:

type var_list;

Here, type must be a valid C data type including char, int, float, double, or any user defined data type etc., and var_list may consist of one or more identifier names separated by commas. Some valid variable declarations along with their definition are shown here:

int a,b,c;
char ch;
float f;
double d;

We can initialize a variable at the time of declaration as follows:

int a=10;

An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists some where else in the program. A variable can be declared multiple times in a program, but it must be defined only once. Following is the declaration of a variable with extern keyword:

extern int a;

| Variable Initialization |

var_name=value;

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:

type var_name=value;

#include<stdio.h>
void main()
{
int a,b,c;
a=10;
b=5;
c=a+b;
printf("\nSum of a and b is:%d",c);
}

 

Union in C

Welcome to Wind Trainers :: Trainers, C, Tutorials, Programming, Java, VB.net, C++, ANSI, Learn C, Learn Programming
Forum | Contact

C Tutorials


| Union in C |


A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.

| Defining an Union |

To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows:

union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str:

union Data
{
int i;
float f;
char str[20];
} data;

Now a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable ie. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.

The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string. Following is the example which will display total memory size occupied by the above union:

#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}

| Accessing Union Members |

To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type. Following is the example to explain usage of union:

#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}

TypeDef in C

Welcome to Wind Trainers :: Trainers, C, Tutorials, Programming, Java, VB.net, C++, ANSI, Learn C, Learn Programming
Forum | Contact

C Tutorials


| typedef |


The C programming language provides a keyword called typedef which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers:

typedef unsigned char BYTE;

After this type definitions, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:.

BYTE b1, b2;

By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows:

typedef unsigned char byte;

You can use typedef to give a name to user defined data type as well. For example you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows:

#include <stdio.h>
#include <string.h>
typedef struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;
int main( )
{
Book book;
strcpy( book.title, "C Programming Language ");
strcpy( book.author, "Wind Trainers ");
strcpy( book.subject, "C Tutorial");
book.book_id = 1234567;
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);

return 0;
}

| typedef and #define |


The #define is a C-directive which is also used to define the aliases for various data types similar to typedef but with three differences:

1. The typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, like you can define 1 as ONE etc.
2. The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor.

#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main( )
{
printf( "Value of TRUE : %d\n", TRUE);
printf( "Value of FALSE : %d\n", FALSE);

return 0;
}

 

Type Casting in C

Welcome to Wind Trainers :: Trainers, C, Tutorials, Programming, Java, VB.net, C++, ANSI, Learn C, Learn Programming
Forum | Contact

C Tutorials


| Type Casting |


Typecasting is a way to convert a variable from one data type to another data type. For example if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows:

type_name expression

Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation:

#include <stdio.h>
main()
{
int sum = 15, count = 4;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}

It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.

Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are necessary.


| Integer Promotion |

Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either to int or unsigned int. Consider an example of adding a character in an int:

#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}

Here value of sum is coming as 116 because compiler is doing integer promotion and converting the value of 'c' to ascii before performing actual addition operation.

| Using Arithmetic Conversion |

The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first performs integer promotion, if operands still have different types then they are converted to the type that appears highest in the following hierarchy:

Usual Arithmetic Conversion
The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us take following example to understand the concept:

#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}

When the above code is compiled and executed, it produces the following result:

Value of sum : 116.000000

Here it is simple to understand that first c gets converted to integer but because final value is double, so usual arithmetic conversion applies and compiler convert i and c into float and add them yielding a float result.

Strings in C

Welcome to Wind Trainers :: Trainers, C, Tutorials, Programming, Java, VB.net, C++, ANSI, Learn C, Learn Programming
Forum | Contact

C Tutorials


| Strings in C |


The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";

String Presentation in C/C++

#include <stdio.h>
void main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
}

Function and Purpose
strcpy(s1, s2);
Copies string s2 into string s1.
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
strlen(s1);
Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

 

#include <stdio.h>


#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}

Scope Rules in C

Welcome to Wind Trainers :: Trainers, C, Tutorials, Programming, Java, VB.net, C++, ANSI, Learn C, Learn Programming
Forum | Contact

C Tutorials


| Scope Rules |


A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable can not be accessed. There are three places where variables can be declared in C programming language:

1. Inside a function or a block which is called local variables.
2. Outside of all functions which is called global variables.
3. In the definition of function parameters which is called formal parameters.

| Local Variables |

Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables. Here all the variables a, b and c are local to main() function.

#include <stdio.h>
void main ()
{
/* local variable declaration */
int a, b;
int c;
a = 10;
b = 20;
c = a + b;
printf ("\nvalue of c = %d",c);
}

| Global Variables |

Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:

#include <stdio.h>
/* global variable declaration */
int c;
void main ()
{
/* local variable declaration */
int a, b;
a = 10;
b = 20;
c = a + b;
printf ("\nvalue of c = %d",c);
}

| Formal Parameters |


A function parameters, formal parameters, are treated as local variables with-in that function and they will take preference over the global variables.

#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("\nValue of a in main() = %d", a);
c = sum( a, b);
printf ("\nValue of c in main() = %d", c);
return 0;
}
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}