Vous êtes sur la page 1sur 143

C Language

What is the purpose of main( ) function ? It is the starting function It returns an int value to the environment that called the program Recursive call is allowed for main( ) also. It is a user-defined function Program execution ends when the closing brace of the function main( ) is reached. It has two arguments 1)argument count and 2) argument vector (represents strings passed). Any user-defined name can also be used as parameters for main( ) instead of argc and argv

What will the preprocessor do for a program ?

The C preprocessor is used to modify your program according to the preprocessor directives in your source code. A preprocessor directive is a statement (such as #define) that gives the preprocessor specific instructions on how to modify your source code. The preprocessor is invoked as the first part of your compiler programs compilation step. It is usually hidden from the programmer because it is run automatically by the compiler. The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code. This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments.

What is the heap ?

Recursive data structures are almost always implemented with memory from the heap. Strings often come from there too, especially strings that could be very long at runtime. If you can keep data in a local variable (and allocate it from the stack), your code will run faster than if you put the data on the heap. Sometimes you can use a better algorithm if you use the heap faster, or more robust, or more flexible. Its a tradeoff. If memory is allocated from the heap, its available until the program ends. Thats great if you remember to deallocate it when youre done. If you forget, its a problem

Pointer Near Pointer Far Pointer

void main(){ int x=10; int far *ptr; Int *p; ptr=&x; printf("%d %d",sizeof(ptr), sizeof(p)); }


void main(){ int far *p,far *q; printf("%d %d",sizeof(p) ,sizeof(q)); }

4 4

void main(){ int x=100; int far *ptr; ptr=&x; printf("%Fp",ptr); }


void main(){ int far *p=(int *)0X70230000; int far *q=(int *)0XB0210000; if(p==q) printf("Both pointers are equal"); else printf("Both pointers are not equal"); }

Output: Both pointers are not equal

void main(){ int far *p=(int *)0X70230000; int far *q=(int *)0XB0210000; int near *x,near*y; x=(int near *)p; y=(int near *)q; if(x==y) printf("Both pointer are equal"); else printf("Both pointer are not equal"); }

Output: Both pointers are equal

A void pointer is a C convention for a raw address. The compiler has no idea what type of object a void Pointer really points to. If you write int *ip; ip points to an int. If you write void *p; p doesnt point to a void


Calloc(m, n) is essentially equivalent to p = malloc(m*n); memset(p, 0, m*n); The zero fill is all-bits-zero, and does not therefore guarantee useful null pointer values or floating-point zero values. 'Free' is useable to release the memory allocated by malloc or calloc.

Malloc(s); returns a pointer for enough storage for an object of s bytes. Calloc(n,s); returns a pointer for enough contiguous storage for n objects, each of s bytes. The storage is all initialized to zeros.

What is the purpose of realloc( ) ? The function realloc(ptr,n) uses two arguments. the first argument ptr is a pointer to a block of memory for which the size is to be altered. The second argument n specifies the new size. The size may be increased or decreased. If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( ) may create a new region and all the old data are moved to the new region.

Why n++ executes faster than n+1 ? The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas, n+1 requires more instructions to carry out this operation.

What are the standard predefined macros ? The ANSI C standard defines six predefined macros for use in the C language: Macro Name Purpose _ _LINE_ _ Inserts the current source code line number in your code. _ _FILE_ _ Inserts the current source code filename in your code. _ _ Inserts the current date of compilation in your code. _ _TIME_ _ Inserts the current time of compilation in your code. _ _STDC_ _ Is set to 1 if you are enforcing strict ANSI C conformity. _ _cplusplus Is defined if you are compiling a C++ program.

What is the easiest sorting method to use ? The answer is the standard library function qsort(). Its the easiest sort by far for several reasons: It is already written. It is already debugged. It has been optimized as much as possible (usually). Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2));

What is the benefit of using const for declaring constants ?

The benefit of using the const keyword is that the compiler might be able to make optimizations based on the knowledge that the value of the variable will not change. The reason to use const rather than #define to define a constant is that a const variable can be of any type (such as a struct, which cant be represented by a #defined constant). Also, because a const variable is a real variable, it has an address that can be used, if needed, and it resides in only one place in memory

How do you use a pointer to a function ? int strcmp(const char *, const char * ) int (*pf)( const char *, const char * ); pf = strcmp;

Static local variable Static Global variable Global Variable Extern

void main() { float a= 0.7; if (a < 0.7) printf("c"); else printf("c++"); }

Output of the above program is c.

extern int i=10; void main() { i=20; printf("%d",i); }

O/P: 20

main() { if (!(1&&0)) { printf("OK I am done."); } else { printf("OK I am gone."); } }

void main () { int x = 10; printf ("x = %d, y = %d", x,--x++); }

O/P: L Vallue Required

main() { printf(%d); }

O/P Garbage Value

What is the Use of Static? 1. Static Variable 2. Static Method 3. Global Static Variable

extern int i; void main() { i=20; printf("%d",i); }

O/P linker Error Undefined Symbol I in the module

Difference between

const char* p and char const* p?

main() { int i; float *pf; pf = (float *)&i; *pf = 100.00; printf("n %d", i); }

Answer 0

What would be the output of the following program. #include<stdio.h> main() { extern int a; printf("%d",a);; } int a=20; (a) 20 (b) 0 (c) garbage value (d) error!!

Answer Garbage Value

What would be the output of the following program. main() { int a[5]={2,3}; printf("\n %d %d %d",a[2],a[3],a[4]); } (a) garbage value (b) 2 3 3 (c) 3 2 2 (d) 0 0 0

(d) 0

What would be the output of the following program. main() { int i=-3,j=2,k=0,m; m=++i&&++j||++k; printf("\n %d %d %d %d",i,j,k,m); } (a) -2 3 0 1 (b) -3 2 0 1 (c) -2 3 1 1 (d) error

(a) -2

void main() { int d=5; printf("%f",d); }

Ans.: Undefined

void main() { int i; for(i=1;i<4,i++) switch(i) case 1: printf("%d",i);break; { case 2:printf("%d",i);break; case 3:printf("%d",i);break; } switch(i) case 4:printf("%d",i); }

Ans.: 1,2,3,4

void main() { float j; j=1000*1000; printf("%f",j); } 1. 1000000 2. Overflow 3. Error 4. None

Ans.: 4 None

void main() { int i=7; printf("%d",i++*i++); }

Ans.: 56

#define one 0 #ifdef one printf("one is defined "); #ifndef one printf("one is not defined ");

Ans.: "one is defined"

void main() { intcount=10,*temp,sum=0; temp=&count; *temp=20; temp=&sum; *temp=count; printf("%d %d %d ",count,*temp,sum); }

Ans.: 20 20 20

main() { static i=3; printf("%d",i--); return i>0 ? main():0; }

Ans.: 321

char *foo() { char result[100]); strcpy(result,"anything is good"); return(result); } void main() { char *j; j=foo() printf("%s",j); }

Ans.: anything is good.

main() { char *p1="Name"; char *p2; p2=(char *)malloc(20); while(*p2++=*p1++); printf("%s\n",p2); }

Ans.. An empty string

main() { int x=5; printf("%d %d %d\n",x,x<<2,x>>2); }

Ans.. 5 20 1

char *ptr = "Ramco Systems"; (*ptr)++; printf("%s\n",ptr); ptr++; printf("%s\n",ptr); }

Ans.. Samco Systems Amco Systems

#include<stdio.h> main() { char *p1; char *p2; p1=(char *) malloc(25); p2=(char *) malloc(25); strcpy(p1,"Ramco"); strcpy(p2,"Systems"); strcat(p1,p2); printf("%s",p1); }

Ans.. RamcoSystems

# define TRUE 0 some code while(TRUE) { some code }

Ans.. This won't go into the loop as TRUE is defined as 0

main() { int a=0; if(a=0) printf("Ramco Systems\n"); else printf("Ramco Systems\n"); }

Ans.. Ony one time "Ramco Systems" will be printed

#include<stdio.h> void main(void); static int i=50; int print(int i); void main(void) { static int i=100; while(print(i)) { printf("%d\n",i); i--; } } int print(int x) { static int i=2; return(i--); }

Ans 100 99

#define SQR(x) (x*x) main() { int a,b=3; a= SQR(b+2); printf("%d",a); } a) 25 b) 11 c) error d) garbage value


main() { const char *fun(); *fun()='A'; } const char *fun() { return "Hello"; }

Cannot Modify Constant Object

main() { const int x=5; int *ptrx; ptrx=&x; *ptrx=10; printf("%d",x); }


main() { const int x=5; x=10; printf("%d",x); }

Cannot Modify constant Object

int func(int i) { if(i%2)return 0; else return 1; } main() { int =3; i=func(i); i=func(i); printf("%d",i); }

main() { const int x; x=128; printf("%d",x); }

Cannot Modify Constant Object

#include <stdio.h> struct my_struct { int p:1; int q:1; int r:6; int s:2; }; struct my_struct bigstruct; struct my_struct1 { char m:1; }; struct my_struct1 smallstruct; void main (void) { printf ("%d %d\n",sizeof (bigstruct),sizeof (smallstruct)); }

2 1


Feature Paradigms C Procedural C++ Procedural, OOP, Generic Programming Executable Native Code Manual Java OOP, Generic Programming (from Java 5) Java bytecode Managed, using a garbage collector No pointers; references are used instead. No

Form of Executable Compiled Source Native Code Code Memory management Manual



Yes, very commonly used, Yes, very but some form commonly used. of references available too. Yes Yes

Character arrays Complex Data Structures, Types unions String Type



Character Objects arrays, objects Structures, Classes unions, classes Single class inheritance, Multiple class multiple interface inheritance implementatio n Yes No

Operator Overloading Automatic coercions


Not at all if Yes, with Yes, with loss could warnings if loss warnings if loss occur; msut could occur could occur cast explicitly






UNDERSTANDING STATIC 1. They Can only Call Other Static Methods 2. They must only access static data 3. They cannot refer to this or super in any way

class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } }

O/P Static Block Initialized X=42 A=3 B=12

Understanding Final 1. Declare Constants if you declare variable using final keyword 2. Prevent Method Overriding if you declare method using final keyword 3. Prevent Inheritance if you declare a class using final keyword

Understanding SUPER 1.Call super class constructor super(arguments); 2.Access instance variables(Prevent Name Hiding) super.instancevariable;

When Constructors are called? In Class hierarchy constructors are called in order of derivation i.e., from Super Class to Sub Class

class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); }

// overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } }

when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass

class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; }

// display k this overrides show() in A void show() { System.out.println("k: " + k); } } class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls show() in B } }


Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements runtime polymorphism.


Feature Multiple inheritance Interface A class may inherit several interfaces. Abstract class A class may inherit only one abstract class. An interface cannot An abstract class can provide any code, just provide complete, the signature. default code and/or just the details that have to be overridden. An interface cannot An abstract class can have access modifiers contain access for the subs, functions, modifiers for the subs, properties etc functions, properties everything is assumed as public

Default implementation

Access Modfiers


Adding functionality (Versioning)

Requires more time to find the actual method in the corresponding classes. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.


If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Thus, process-based multitasking is the feature that allows your computer to run two or more programs concurrently. In processbased multitasking, a program is the smallest unit of code that can be dispatched by the scheduler

In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously.


Retur Method Description n Type currentThrea Returns an object reference to the thread in Thread d( ) which it is invoked. Retrieve the name of the thread object or getName( ) String instance. start( ) void Start the thread by calling its run method. This method is the entry point to execute run( ) void thread, like the main method for applications. Suspends a thread for a specified amount of sleep( ) void time (in milliseconds). boolea This method is used to determine the thread is isAlive( ) n running or not.

This method returns the number of active activeCount( ) int threads in a particular thread group and all its subgroups. The method interrupt the threads on which it is interrupt( ) void invoked. By invoking this method the current thread yield( ) void pause its execution temporarily and allow other threads to execute. This method and join(long millisec) Throws InterruptedException. These two methods are join( ) void invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively.

Synchroniztion When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. Deadlock A state of execution when 2 or more threads are all put on hold, because each of them is holding a synchronization lock while waiting for another lock

How to Run Garbage Collector Explicitly This section provides a tutorial example on how to run the Garbage Collector explicitly by calling the gc() method on the Runtime instance.


Serialization Converting an object state persistent i.e., converting an object into stream of bytes De-Serialization Converting an stream of bytes into Object Transient if u declare variable with transient keyword then the value of the variable is not persistent

Volatile When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.


1. Bootstrap ClassLoadder The root ClassLoader: Created by the JVM and represented as "null". Responsible to load JVM system classes located in <JAVA_HOME>/lib folder. 2. Extensions ClassLoadder Created by the JVM and represented as a sun.misc.Launcher$ExtClassLoader object. Responsible to load JVM extension classes located in <JAVA_HOME>/lib/ext folder. 3. System ClassLoadder Created by the JVM and represented as a sun.misc.Launcher$AppClassLoader object. Responsible to load Application classes specified in the "classpath".