c Interview Qsns

Embed Size (px)

Citation preview

  • 8/4/2019 c Interview Qsns

    1/31

    SRAVANICHOWDARY.B

    1

    1. Differences between c and c++? C is a structured programming language; c++ is object oriented programming language. C is modular programming language; c++ is object oriented programming language. No dynamic allocation in C; In C++ we can.

    2.

    Differences between main () in c and main () in C++? C main () returns void; C++ main () returns integer value. Main () in c required because it indicates starting point of program; main () in c++

    needed because system needs to declare it and program needs to define it. System needs

    means processor needs to declare STD library functions available. Program needs to

    define it means object need to be created in main () so that they can be called with respect

    to method.

    3. Is it possible to execute code even after the program exits the main () function?4. What is the difference between NULL and NUL?

    NULL is macro defined in for the null pointer; NUL is a user definedvariable.

    Basically NULL is a pre defined variable. We cant define value for NULL;NUL isdefined by user and its value changed by user time to time according to its

    requirements.

    5. Can we execute printf statement without using semicolon?Printf is built in function and we know that when we are calling a function, we need to

    put a semicolon after the calling statement. We cant execute printf statement without

    semicolon.

    6. Can we write a C program without using main () function?We can write the program without main (), but we can run that program.

    7. How can you avoid including a header more than once?By using #define.

    8. Is it possible to print graphics output in c?Yes, we can print by using APIs defined in #include.

    9. How to perform adition and subtraction without using addition, subtraction operators?Addition: #include #include

    Void main()

    {

    Int a, b,c,i;

    Scanf(%d%d,&a, &b);For(i=1;i

  • 8/4/2019 c Interview Qsns

    2/31

    SRAVANICHOWDARY.B

    2

    Subtraction: #include

    #include

    Void main()

    {

    Int a, b,i;

    Printf(enter a b);

    Scanf(%d%d,&a, &b);

    For(i=1;i

  • 8/4/2019 c Interview Qsns

    3/31

    SRAVANICHOWDARY.B

    3

    code contains any conditional preprocessor directives (such as #if), the preprocessor

    evaluates the condition and modifies your source codeaccordingly.

    12.What is :- Asembler , compiler , Preprocessor , laxical analysis , parsing ? Assembler:It converts the assembly language into machine level.

    Compiler:It converts the high level program into machine level.

    Preprocessor: Already defined using #define and used later in the program.

    Lexical analysis:It analyze the expression from left to right and separate into tokens.

    Parsing:It groups the token collected from the lexical analyser and constructs parse tree.

    13.Is there anything you can do in C++ that you cannot do in C ?WE CAN PROGRAMED Any thing in C/C++

    BUT C++ GIVE MORE RE-USABILITY,

    AND IT'S A OBJECT ORIENTED LANGUAGE

    THE THING WHICH ARE NOT SUPPORTED BY C ARE-

    1) INHERITANCE

    2) POLYMORPHISM3) OPERATOR OVER LOADING

    4) ABSTRACTION(DATA HIDING)

    AND OTHER OOP's FEATURE

    14.What is # used for?To set the line numbers.

    15.What are the applications and advantages of C-language?1.'C' is the only intermediate programming language in between low level and high

    level programminglanguage.

    2.All applications written in "C" will be executed fast.3.All aeronautical applications , mission critical applications are written in "C".

    4.Embedded programming is written in "C".

    16.What is the difference between compile time error and run time error? Compile time is semantic and syntax error, whereas run time is memory allocation errore.g. segmentation fault. If the program has the runtime error then the program would

    compile successfully with no erros. But the out put was not desired.

    eg: dividing with zero.

    17.What are the characteristics of arrays in C?An array holds elements that have the same data type

    Array elements are stored in subsequent memory locations

    Two-dimensional array elements are stored row by row in subsequent memory

    locations.

    Array name represents the address of the starting element

    Array size should be mentioned in the declaration. Array size must be a constant

    expression and not a variable.

  • 8/4/2019 c Interview Qsns

    4/31

    SRAVANICHOWDARY.B

    4

    18.What are the different storage classes in C?C contains 4 types of storage classes:

    1.Automatic:

    auto-Local variable which is known only to the function in which it is declared.

    2.Extern:

    Global variable which known to all functions in the file.

    3.Static:

    Local or global variable which exists & retain its value even after control is transferred to

    calling function.

    4.Register:

    Local variable which is stored in register instead of memory.

    19.Can Any other language completely replace c?*The primary design of C is to produce portable code while maintaining performance and

    minimizing footprint, as is the case for operating systems or other programs where a

    "high-level" interface would affect performance.* It is a stable and mature language whose features are unlikely to disappear for a long

    time and has been ported to most, if not all, platforms.

    For example, C programs can be compiled and run on the HP 50g calculator (ARM

    processor), the TI-89calculator (68000 processor), Palm OS Cobalt smartphones (ARM

    processor). While nearly all popular programming languages will run on at least one of

    these devices, C may be the only programming language that runs on more than 3 of

    these devices.

    *One powerful reason is memory allocation. Unlike most computer languages, C allows

    the programmer to write directly to memory.

    * C gives control over the memory layout of data structures. Moreover dynamic memory

    allocation is under the control of the programmer, which inevitably means that memory

    deallocation is the burden of the programmer.

    *While Perl, PHP, Python and Ruby may be powerful and support many features not

    provided by default in C, they are not normally implemented in their own language.

    *Rather, most such languages initially relied on being written in C (or another high-

    performance programming language), and would require their implementation be ported

    to a new platform before they can be used.

    *As with all programming languages, whether you want to choose C over another high-

    level language is a matter of opinion and both technical and business requirements.

    20.Why two pointers cannot be added in c language?Pointer is a variable which holds the address of other variables.Adding a 2 pointer

    variable is equivalent to adding 2 addresses. Of course the addresses are unknown hence

    resulting again to a unknown address,thus pointing to unknown memory location. Where

    in no one knows what is stored in the resultant memory location,which is meaningless..

  • 8/4/2019 c Interview Qsns

    5/31

    SRAVANICHOWDARY.B

    5

    e.g.. int *p1, *p2, *p3;

    p3 = p1 + p2;

    If p1 and p2 are 4 digit address, then p3 will be of 5 digit which does not exist.

    21.write a program for printing when i press a key next to the letter in thealphabeticalorder can be printed

    int main()

    {

    char key;

    printf("Enter from which u wnat to see the alphabets

    ");

    scanf("%c",&key);

    do

    {

    printf(" %c",key);

    }while (key++ != 'z');}

    22.What is the difference between null array and an empty array?null array:means array size is not declared i.e int a[];

    empty array:array size is declared but no values contain in array

    ie. int a[10];

    23.Code for swapping of two numbers without using temporary variable using C.int a=10,b=5;

    a=a+b; // a=15

    b=a-b; // b=10

    a=a-b; // a=5

    24.if "condition"printf("Hello");

    else

    printf("World")

    what should be the condition,

    so the output will be HelloWorld.

    if(!printf("hello"))

    printf("hello");

    else

    printf("world");

    25.Is it better to use malloc() or calloc()?Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each

    operates slightly different from the other. malloc() takes a size and returns a pointer to a

    chunk of memory at least that big:

  • 8/4/2019 c Interview Qsns

    6/31

    SRAVANICHOWDARY.B

    6

    void *malloc( size_t size );

    calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of

    memory

    at least big enough to hold them all:

    void *calloc( size_t numElements, size_t sizeOfElement );

    There?s one major difference and one minor difference between the two functions. The major

    difference is that malloc() doesn?t initialize the allocated memory. The first time malloc()

    gives you a particular chunk of memory, the memory might be full of zeros. If memory has

    been allocated, freed, and reallocated, it probably has whatever junk was left in it. That

    means, unfortunately, that a program might run in simple cases (when memory is never

    reallocated) but break when used harder (and when memory is reused). calloc() fills the

    allocated memory with all zero bits. That means that anything there you?re going to use as a

    char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you?re

    going to use as a pointer is set to all zero bits. That?s usually a null pointer, but it?s not

    guaranteed.Anything you?re going to use as a float or double is set to all zero bits; that?s afloating-point zero on some types of machines, but not on all.

    The minor difference between the two is that calloc() returns an array of objects;

    malloc() returns one object. Some people use calloc() to make clear that they want an array.

    26.What is the difference between System.String and System.StringBuilder classes?String is immutable.A new object is create if a string needs to be modified.

    While string builder object can be modified without creating a new object.

    stringbuilder class offers various methods like replace etc.

    27.How can I convert a number to a string?The standard C library provides several functions for converting numbers of all formats

    (integers, longs, floats, and so on) to strings and vice versa The following functions can be

    used to convert integers to strings:

    Function Name Purpose

    itoa() Converts an integer value to a string.

    ltoa() Converts a long integer value to a string.

    ultoa() Converts an unsigned long integer value to a string.

    The following functions can be used to convert floating-point values to strings:

    Function Name Purpose

    ecvt() Converts a double-precision floating-point value to a string without an embedded

    decimal point.

    fcvt() Same as ecvt(), but forces the precision to a specified number of digits.

    28.What is the quickest sorting method to use?The Quick Sort

    The quick sort algorithm is of the ?divide and conquer? type. That means it works by

    reducing a sorting

    problem into several easier sorting problems and solving each of them. A ?dividing? value is

  • 8/4/2019 c Interview Qsns

    7/31

    SRAVANICHOWDARY.B

    7

    chosen from the input data, and the data is partitioned into three sets: elements that belong

    before the dividing value, the value itself, and elements that come after the dividing value.

    The partitioning is performed by exchanging elements that are in the first set but belong in

    the third with elements that are in the third set but belong in the first Elements that are equal

    to the dividing element can be put in any of the three sets?the algorithm will still work

    properly.

    The Merge Sort

    The merge sort is a? Divide and conquer? Sort as well. It works by considering the data to be

    sorted as a

    sequence of already-sorted lists (in the worst case, each list is one element long). Adjacent

    sorted lists are merged into larger sorted lists until there is a single sorted list containing all

    the elements. The merge sort is good at sorting lists and other data structures that are not in

    arrays, and it can be used to sort things that don?t fit into memory. It also can be

    implemented as a stable sort.

    The Radix SortThe radix sort takes a list of integers and puts each element on a smaller list, depending on

    the value of its least significant byte. Then the small lists are concatenated, and the process is

    repeated for each more significant byte until the list is sorted. The radix sort is simpler to

    implement on fixed-length data such as ints.

    29.What is the quickest searching method to use?A binary search, such as bsearch() performs, is much faster than a linear search. A hashing

    algorithm can provide even faster searching. One particularly interesting and fast method for

    searching is to keep the data in a ?digital trie.? A digital trie offers the prospect of being able

    to search for an item in essentially a constant amount of time, independent of how many

    items are in the data set.

    A digital trie combines aspects of binary searching, radix searching, and hashing. The term

    ?digital trie? refers to the data structure used to hold the items to be searched. It is a

    multilevel data structure that branches N ways at each level.

    30.Can you use the function fprintf()to display the output on the screen? fprintf( stout, "Hello %s", name );

    this line prints Hello on the console. to print "Hello" in a file, put the file pointer in the place

    of stdout

    eg:

    fprintf( fp, "Hello %s", name );

    31.What is a static function?A static function is a function whose scope is limited to the current source file. Scope refers

    to the visibility of a function or variable. If the function or variable is visible outside of the

    current source file, it is said to have global, or external, scope. If the function or variable is

    not visible outside of the current source file, it is said to have local, or static, scope.

  • 8/4/2019 c Interview Qsns

    8/31

    SRAVANICHOWDARY.B

    8

    32.Is using exit() the same as using return?No. The exit() function is used to exit your program and return control to the operating

    system. The return statement is used to return from a function and return control to the

    calling function. If you issue a return from the main() function, you are essentially returning

    control to the calling function, which is the operating system. In this case, the return

    statement and exit() function are similar

    33.What are the advantages of the functions?1. Code Re usability
    2. Occupies less memory
    3. Resilience 2 change i.e. error

    handling is easy
    4. Logic becomes clear
    5. Compiler takes less time 2 compile the

    program

    34.How would you use the functions randomize()and random()?Random() returns a random number between 0 and (num-1).random(num) is a macro defined

    in stdlib.h

    Randomize() initializes the random number generator with a random value.Because

    randomize is implemented as a macro that calls the time function protyped in time.h,youshould include time.h when you use this routine.

    35.What is a difference between printf and cout and why printf called a function and coutobject as both are used to print data?

    printf is not "called" a function...printf "is" a function. So as for the differences, the biggest

    difference lies in the above statement itself:

    1. While printf if a 'function' defined in stdio.h, cout is actually an object presnt in iostream.h

    2. While printf expects the programmer to specify the type of output variable using format

    string, cout has the ability to output the data without explicitly specifying it's type

    36.Differentiate between a linker and linkage?A linker converts an object code into an executable code by linking together the necessary

    build in functions. The form and place of declaration where the variable is declared in a

    program determine the linkage of variable

    37.What are returned by printf(), scanf() functions,if they return anything means what arethat?

    Return type of printf() and scanf() is integer. scanf() returns the no.of variables used and

    printf() returns the total no.of bytes.

    38.What is the purpose of main( ) function?main is function which must be needed in our program it does'n matter where you write your

    main functionin your program but it will starts execution from main our program will

    compile without main but to RUN it we must need Main() function.Main() behave like

    a function its by default datatype is INT, thats why we cant define a function inside main() as

    we know that we cant define a function within a function we can only call a function from

    other function.when our program starts it first looks for main and than it starts its execution

    from so without main we cant RUN our program.

  • 8/4/2019 c Interview Qsns

    9/31

    SRAVANICHOWDARY.B

    9

    39.How to use the cprintf, cscanf, sscanf, sprintf, vsscanf, vsprintf, vscanf & vprintf?cprintf:This function sends the formatted output to the text window on the screen.

    cscanf:This function reads reads from the standard input device directly,avoiding buffering

    both by DOS and by the library.

    sprintf: This function sends formatted output to the string.

    sscanf: This function scans formatted text from the string and stores i on the variables

    pointed to by the arguments.

    vprintf: This function sends formatted output to stdin,using an argument list.

    vscanf: This function scans formatted text from stdin and stores it in the variables pointed to

    by the arguments.

    vsprintf:This function sends formatted output to the string using argument list.

    vsscanf: This function scans formatted text from the string and stores it in the variables.

    40.How would you use the functions sin(),pow(),sqrt()?before using these functions

    should be included in the programsin(d) will returns the sine of d,

    pow(a,b) will returns a the value a to the power b(a^b)

    eg:pow(2,3) will returns 8;

    sqrt(a) returns the square root of a

    eg: sqrt(4) returns 2;

    41.What is an argument ? differentiate between formal arguments and actualarguments?An argument is an entity used to pass the data from calling function to the called function.

    Formalarguments are the arguments available in the function definition.They are preceded by

    their own data types.Actual arguments are available in the function call.

    arguments are called as parameters .they are

    passed from main function to sub function.

    formal arguments are located in sub function.

    actual arguments are located in function

    the values of actual arguments

    are copied to formal arguments.

    42.What does static variable mean?There are 3 main uses for the static.

    1. If you declare within a function:

    It retains the value between function calls

    2.If it is declared for a function name:

    By default function is extern..so it will be visible from other files if the function declaration

    is as static..it is invisible for the outer files

    3. Static for global variables:

    By default we can use the global variables from outside files If it is static global..that

    variable is limited to with in the file.

  • 8/4/2019 c Interview Qsns

    10/31

    SRAVANICHOWDARY.B

    10

    #include

    int t = 10;

    main(){

    int x = 0;

    void funct1();

    funct1();

    printf("After first call \n");

    funct1();

    printf("After second call \n");

    funct1();

    printf("After third call \n");

    }

    void funct1()

    {

    static int y = 0;int z = 10;

    printf("value of y %d z %d",y,z);

    y=y+10;

    }

    value of y 0 z 10 After first callvalue of y 10 z 10 After second call

    value of y 20 z 10 After third call

    43.Can a variable be both constant and volatile?Yes. The const modifier means that this code cannot change the value of the variable, but thatdoes not mean that the value cannot be changed by means outside this code.

    44.What is the output of printf("%d") ?1. When we write printf("%d",x); this means compiler will print the value of x. But as here,there is nothing after %d so compiler will show in output window garbage value.

    2. When we use %d the compiler internally uses it to access the argument in the stack(argument stack). Ideally compiler determines the offset of the data variable depending on

    the format specification string. Now when we write printf("%d",a) then compiler firstaccesses the top most element in the argument stack of the printf which is %d and depending

    on the format string it calculated to offset to the actual data variable in the memory which isto be printed. Now when only %d will be present in the printf then compiler will calculate the

    correct offset (which will be the offset to access the integer variable) but as the actual data

    object is to be printed is not present at that memory location so it will print what ever will bethe contents of that memory location.

  • 8/4/2019 c Interview Qsns

    11/31

    SRAVANICHOWDARY.B

    11

    3. Some compilers check the format string and will generate an error without the propernumber and type of arguments for things like printf(...) and scanf(...).

    malloc()

    45. What is the difference between printf() and sprintf() ?

    sprintf() writes data to the character array whereas printf(...) writes data to the standardoutput device.

    46. Advantages of a macro over a function ?

    Macro gets to see the Compilation environment, so it can expand __ __TIME__ __FILE__#defines. It is expanded by the preprocessor.

    For example, you cant do this without macros

    #define PRINT(EXPR) printf( #EXPR =%d\n, EXPR)

    PRINT( 5+6*7 ) // expands into printf(5+6*7=%d, 5+6*7 );

    You can define your mini language with macros:#define strequal(A,B) (!strcmp(A,B))

    Macros are a necessary evils of life. The purists dont like them, but without it no real work getsdone.

    47. When should a type cast be used?

    There are two situations in which to use a type cast. The first use is to change the type of anoperand to an arithmetic operation so that the operation will be performed properly.

    The second case is to cast pointer types to and from void * in order to interface with functions

    that expect or return void pointers.

    For example, the following line type casts the return value of the call to malloc() to be a pointerto a foo structure.

    struct foo *p = (struct foo *) malloc(sizeof(struct foo));

    48. What is the stack?

    The stack is where all the functions local (auto) variables are created. The stack also contains

    some information used to call and return from functions.

    A stack trace is a list of which functions have been called, based on this information. When you

    start using a debugger, one of the first things you should learn is how to get a stack trace.

    The stack is very inflexible about allocating memory; everything must be deallocated in exactly

    the reverse order it was allocated in. For implementing function calls, that is all thats needed.Allocating memory off the stack is extremely efficient. One of the reasons C compilers generate

    such good code is their heavy use of a simple stack.

  • 8/4/2019 c Interview Qsns

    12/31

    SRAVANICHOWDARY.B

    12

    There used to be a C function that any programmer could use for allocating memory off thestack. The memory was automatically deallocated when the calling function returned. This was a

    dangerous function to call; its not available anymore.

    Whats the advantage of using System.Text.StringBuilder over System. String?

    String Builder is more efficient in the cases, where a lot of manipulation is done to the text.Strings are immutable, so each time its being operated on, a new instance is created.

    Can you store multiple data types in System. Array?No.

    Whats the difference between the System.Array.CopyTo () and System.Array.Clone ()?The first one performs a deep copy of the array, the second one is shallow.

    How can you sort the elements of the array in descending order?By calling Sort() and then Reverse() methods.

    Whats the .NET datatype that allows the retrieval of data by a unique key?HashTable.

    Whats class SortedList underneath?

    A sorted HashTable.Will finally block get executed if the exception had not occurred?Yes.

    Whats the C# equivalent of C++ catch (), which was a catch-all statement for anypossible exception?A catch block that catches the exception of type System. Exception. You can also omit the

    parameter data type in this case and just write catch {}.

    Can multiple catch blocks be executed?No, once the proper catch code fires off, the control is transferred to the finally block (if there areany), and then whatever follows the finally block.

    Why is it a bad idea to throw your own exceptions?

    Well, if at that point you know that an error has occurred, then why not write the proper code tohandle that error instead of passing a new Exception object to the catch block? Throwing your

    own exceptions signifies some design flaws in the project.

    Whats a delegate?A delegate object encapsulates a reference to a method. In C++ they were referred to as functionpointers.

    Whats a multicast delegate?Its a delegate that points to and eventually fires off several methods.

    Hows the DLL Hell problem solved in .NET?Assembly versioning allows the application to specify not only the library it needs to run (which

    was available under Win32), but also the version of the assembly.

    What are the ways to deploy an assembly?An MSI installer, a CAB archive, and XCOPY command.

    Whats a satellite assembly? When you write a multilingual or multi-cultural application in

    .NET, and want to distribute the core application separately from the localized modules, thelocalized assemblies that modify the core application are called satellite assemblies.

    What namespaces are necessary to create a localized application?System.Globalization, System. Resources.

    Whats the difference between // comments, /* */ comments and /// comments?

  • 8/4/2019 c Interview Qsns

    13/31

    SRAVANICHOWDARY.B

    13

    Single-line, multi-line and XML documentation comments.

    How do you generate documentation from the C# file commented properly with a

    command-line compiler?Compile it with a /doc switch.

    Whats the difference between and XML documentation tag?

    Single line code example and multiple-line code example.Is XML case-sensitive?Yes, so and are different elements.

    What debugging tools come with the .NET SDK?CorDBGcommand-line debugger, and DbgCLRgraphic debugger. Visual Studio .NET uses

    the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

    What does the window show in the debugger?It points to the object thats pointed to by this reference. Objects instance data is shown.

    What does assert () do?In debug compilation, assert takes in a Boolean condition as a parameter, and shows the errordialog if the condition is false. The program proceeds without any interruption if the condition is

    true.Whats the difference between the Debug class and Trace class? Documentation looks the

    same.Use Debug class for debug builds, use Trace class for both debug and release builds.

    Why are there five tracing levels in System.Diagnostics.TraceSwitcher?The tracing dumps can be quite verbose and for some applications that are constantly runningyou run the risk of overloading the machine and the hard drive there. Five levels range from

    None to Verbose, allowing to fine-tune the tracing activities.

    Where is the output of TextWriterTraceListener redirected?To the Console or a text file depending on the parameter passed to the constructor.

    How do you debug an ASP.NET Web application?

    Attach the aspnet_wp.exe process to the DbgClr debugger.What are three test cases you should go through in unit testing?Positive test cases (correct data, correct output), negative test cases (broken or missing data,

    proper handling), exception test cases (exceptions are thrown and caught properly).

    Can you change the value of a variable while debugging a C# application?Yes, if you are debugging via Visual Studio.NET, just go to immediate window.

    Explain the three services model (three-tier application).Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

    What are advantages and disadvantages of Microsoft-provided data provider classes in

    ADO.NET?SQLServer.NET data provider is high-speed and robust, but requires SQL Server license

    purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle,DB2, Microsoft Access and Informix, but its a .NET layer on top of OLE layer, so not the

    fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility

    to ODBC engines.

    Whats the role of the Data Reader class in ADO.NET connections?It returns a read-only dataset from the data source when the command is executed.

  • 8/4/2019 c Interview Qsns

    14/31

    SRAVANICHOWDARY.B

    14

    What is the wildcard character in SQL? Lets say you want to query database with LIKE

    for all employees whose name starts with La.The wildcard character is %, the proper query with LIKE would involve La%.

    Explain ACID rule of thumb for transactions.Transaction must be Atomic (it is one unit of work and does not dependent on previous and

    following transactions), Consistent (data is either committed or roll back, no in-between casewhere something has been updated and something hasnt), Isolated (no transaction sees the

    intermediate results of the current transaction), Durable (the values persist if the data had beencommitted even if the system crashes right after).

    What connections does Microsoft SQL Server support?Windows Authentication (via Active Directory) and SQL Server authentication (via MicrosoftSQL Server username and passwords).

    Which one is trusted and which one is untrusted?Windows Authentication is trusted because the username and password are checked with the

    Active Directory; the SQL Server authentication is untrusted, since SQL Server is the onlyverifier participating in the transaction.

    Why would you use untrusted verificaion?Web Services might use it, as well as non-Windows applications.

    What does the parameter Initial Catalog define inside Connection String?The database name to connect to.

    Whats the data provider name to connect to Access database?Microsoft. Access.

    What does dispose method do with the connection object?Deletes it from the memory.

    What is a pre-requisite for connection pooling?Multiple processes must agree that they will share the same connection, where every parameter

    is the same, including the security settings.

    1.

    What will print out?main (){

    char *p1=name;

    char *p2;p2=(char*)malloc(20);

    memset (p2, 0, 20);

    while(*p2++ = *p1++);printf(%sn,p2);

    }

    Answer:empty string.

    2. What will be printed as the result of the operation below: main()

    {

    int x=20,y=35;

    x=y++ + x++;y= ++y + ++x;

    printf(%d%dn,x,y);

  • 8/4/2019 c Interview Qsns

    15/31

    SRAVANICHOWDARY.B

    15

    }

    Answer : 5794

    3. What will be printed as the result of the operation below: main()

    {int x=5;printf(%d,%d,%dn,x,x< >2);

    }

    Answer: 5,20,1

    4. What will be printed as the result of the operation below: #define swap(a,b) a=a+b;b=a-b;a=a-b;

    void main(){

    int x=5, y=10;

    swap (x,y);printf(%d%dn,x,y);

    swap2(x,y);

    printf(%d%dn,x,y);}

    int swap2(int a, int b)

    {

    int temp;temp=a;

    b=a;

    a=temp;

    return 0; }

    Answer: 10, 5

    10, 5

    5. What will be printed as the result of the operation below: main()

    {

    char *ptr = Cisco Systems;*ptr++; printf(%sn,ptr);

    ptr++;

    printf(%sn,ptr);

    }

    Answer:Cisco Systems

    isco systems

    6. What will be printed as the result of the operation below: main()

    {

    char s1[]=Cisco;

  • 8/4/2019 c Interview Qsns

    16/31

    SRAVANICHOWDARY.B

    16

    char s2[]= systems;printf(%s,s1);

    }

    Answer: Cisco

    7. What will be printed as the result of the operation below: main(){

    char *p1;char *p2;

    p1=(char *)malloc(25);

    p2=(char *)malloc(25);

    strcpy(p1,Cisco);

    strcpy(p2,systems);

    strcat(p1,p2);

    printf(%s,p1);

    }

    Answer: Ciscosystems

    8. The following variable is available in file1.c, who can access it?:static int average;

    Answer: all the functions in the file1.c can access the variable.

    9. WHat will be the result of the following code?#define TRUE 0 // some codewhile(TRUE)

    { // some code

    }

    Answer: This will not go into the loop as TRUE is defined as 0.

    10.What will be printed as the result of the operation below: int x;

    int modifyvalue(){

    return(x+=10);

    }int changevalue(int x)

    {

    return(x+=1);

    }

    void main()

    {

    int x=10;x++;

    changevalue(x);

  • 8/4/2019 c Interview Qsns

    17/31

    SRAVANICHOWDARY.B

    17

    x++;modifyvalue();

    printf("First output:%dn",x);

    x++;changevalue(x);

    printf("Second output:%dn",x);modifyvalue();

    printf("Third output:%dn",x);}

    Answer: 12, 13, 13

    11.What will be printed as the result of the operation below: main()

    {

    int x=10, y=15;

    x = x++;

    y = ++y;printf(%d%dn,x,y);

    }

    Answer: 11, 16

    12.What will be printed as the result of the operation below: main()

    {int a=0;

    if(a==0)

    printf(CiscoSystemsn);

    printf(CiscoSystemsn);}

    Answer: Two lines with Cisco Systems will be printed.

    What is encapsulation??

    Containing and hiding information about an object, such as internal data structures and code.

    Encapsulation isolates the internal complexity of an object's operation from the rest of the

    application. For example, a client component asking for net revenue from a business object need

    not know the data's origin.

    What is inheritance?

    Inheritance allows one class to reuse the state and behavior of another class. The derived class

    inherits the properties and method implementations of the base class and extends it by overridingmethods and adding additional properties and methods.

  • 8/4/2019 c Interview Qsns

    18/31

    SRAVANICHOWDARY.B

    18

    What is Polymorphism??

    Polymorphism allows a client to treat different objects in the same way even if they were created

    from different classes and exhibit different behaviors.

    You can use implementation inheritance to achieve polymorphism in languages such as C++ andJava.

    Base class object's pointer can invoke methods in derived class objects.

    You can also achieve polymorphism in C++ by function overloading and operator overloading.

    What is constructor or ctor?

    Constructor creates an object and initializes it. It also creates vtable for virtual functions. It isdifferent from other methods in a class.

    What is destructor?

    Destructor usually deletes any extra resources allocated by the object.

    What is default constructor?

    Constructor with no arguments or all the arguments has default values.

    What is copy constructor?

    Constructor which initializes the it's object member variables ( by shallow copying) with anotherobject of the same class. If you don't implement one in your class then compiler implements one

    for you.

    for example:

    Boo Obj1(10); // calling Boo constructor

    Boo Obj2(Obj1); // calling boo copy constructor

    Boo Obj2 = Obj1;// calling boo copy constructor

    When are copy constructors called?

    Copy constructors are called in following cases:

    a) when a function returns an object of that class by value

    b) when the object of that class is passed by value as an argument to a function

    c) when you construct an object based on another object of the same classd) When compiler generates a temporary object

  • 8/4/2019 c Interview Qsns

    19/31

    SRAVANICHOWDARY.B

    19

    What is assignment operator?

    Default assignment operator handles assigning one object to another of the same class. Member

    to member copy (shallow copy)

    What are all the implicit member functions of the class? Or what are all the functionswhich compiler implements for us if we don't define one.??

    default ctorcopy ctor

    assignment operator

    default destructoraddress operator

    What is conversion constructor?

    constructor with a single argument makes that constructor as conversion ctor and it can be usedfor type conversion.

    for example:

    class Boo

    {

    public:Boo( int i );

    };

    Boo BooObject = 10 ; // assigning int 10 Boo object

    What is conversion operator??

    class can have a public method for specific data type conversions.

    for example:

    class Boo{

    double value;

    public:

    Boo(int i )operator double()

    {

    return value;}

    };

    Boo BooObject;

  • 8/4/2019 c Interview Qsns

    20/31

    SRAVANICHOWDARY.B

    20

    double i = BooObject; // assigning object to variable i of type double. now conversion operatorgets called to assign the value.

    What is diff between malloc()/free() and new/delete?

    malloc allocates memory for object in heap but doesn't invoke object's constructor to initiallizethe object.

    new allocates memory and also invokes constructor to initialize the object.

    malloc() and free() do not support object semantics

    Does not construct and destruct objectsstring * ptr = (string *)(malloc (sizeof(string)))

    Are not safe

    Does not calculate the size of the objects that it construct

    Returns a pointer to void

    int *p = (int *) (malloc(sizeof(int)));int *p = new int;

    Are not extensiblenew and delete can be overloaded in a class

    "delete" first calls the object's termination routine (i.e. its destructor) and then releases the spacethe object occupied on the heap memory. If an array of objects was created using new, then

    delete must be told that it is dealing with an array by preceding the name with an empty []:-

    Int_t *my_ints = new Int_t[10];

    delete []my_ints;

    what is the diff between "new" and "operator new" ?

    "operator new" works like malloc.

    What is difference between template and macro??

    There is no way for the compiler to verify that the macro parameters are of compatible types.

    The macro is expanded without any special type checking.

    If macro parameter has a postincremented variable ( like c++ ), the increment is performed two

    times.

    Because macros are expanded by the preprocessor, compiler error messages will refer to the

    expanded macro, rather than the macro definition itself. Also, the macro will show up inexpanded form during debugging.

  • 8/4/2019 c Interview Qsns

    21/31

    SRAVANICHOWDARY.B

    21

    for example:

    Macro:

    #define min(i, j) (i < j ? i : j)

    template:

    template

    T min (T i, T j){

    return i < j ? i : j;

    }

    What are C++ storage classes?

    auto

    registerstatic

    extern

    auto: the default. Variables are automatically created and initialized when they are defined and

    are destroyed at the end of the block containing their definition. They are not visible outside thatblock

    register: a type of auto variable. a suggestion to the compiler to use a CPU register for

    performance

    static: a variable that is known only in the function that contains its definition but is neverdestroyed and retains its value between calls to that function. It exists from the time the program

    begins execution

    extern: a static variable whose definition and placement is determined when all object and

    library modules are combined (linked) to form the executable code file. It can be visible outside

    the file where it is defined.

    What are storage qualifiers in C++ ?

    They are..

    const

    volatile

    mutable

    Const keyword indicates that memory once initialized, should not be altered by a program.

  • 8/4/2019 c Interview Qsns

    22/31

    SRAVANICHOWDARY.B

    22

    volatile keyword indicates that the value in the memory location can be altered even thoughnothing in the program

    code modifies the contents. for example if you have a pointer to hardware location that contains

    the time, where hardware changes the value of this pointer variable and not the program. Theintent of this keyword to improve the optimization ability of the compiler.

    mutable keyword indicates that particular member of a structure or class can be altered even if aparticular structure variable, class, or class member function is constant.

    struct data{

    char name[80];

    mutable double salary;

    }

    const data MyStruct = { "Satish Shetty", 1000 }; //initlized by complier

    strcpy ( MyStruct.name, "Shilpa Shetty"); // compiler error

    MyStruct.salaray = 2000 ; // complier is happy allowed

    What is reference ??

    reference is a name that acts as an alias, or alternative name, for a previously defined variable or

    an object.

    prepending variable with "&" symbol makes it as reference.

    for example:

    int a;int &b = a;

    What is passing by reference?

    Method of passing arguments to a function which takes parameter of type reference.

    for example:

    void swap( int & x, int & y )

    {int temp = x;

    x = y;

    y = temp;}

    int a=2, b=3;

  • 8/4/2019 c Interview Qsns

    23/31

    SRAVANICHOWDARY.B

    23

    swap( a, b );

    Basically, inside the function there won't be any copy of the arguments "x" and "y" instead they

    refer to original variables a and b. so no extra memory needed to pass arguments and it is moreefficient.

    When do use "const" reference arguments in function?

    a) Using const protects you against programming errors that inadvertently alter data.b) Using const allows function to process both const and non-const actual arguments, while a

    function without const in the prototype can only accept non constant arguments.c) Using a const reference allows the function to generate and use a temporary variable

    appropriately.

    When are temporary variables created by C++ compiler?

    Provided that function parameter is a "const reference", compiler generates temporary variable infollowing 2 ways.

    a) The actual argument is the correct type, but it isn't Lvalue

    double Cube(const double & num)

    {

    num = num * num * num;return num;

    }

    double temp = 2.0;

    double value = cube(3.0 + temp); // argument is a expression and not a Lvalue;

    b) The actual argument is of the wrong type, but of a type that can be converted to the correcttype

    long temp = 3L;double value = cuberoot ( temp); // long to double conversion

    What is virtual function?

    When derived class overrides the base class method by redefining the same function, then ifclient wants to access redefined the method from derived class through a pointer from base class

    object, then you must define this function in base class as virtual function.

    class parent

    {void Show()

    {

    cout

  • 8/4/2019 c Interview Qsns

    24/31

    SRAVANICHOWDARY.B

    24

    }};

    class child: public parent{

    void Show(){cout show() i

    now we goto virtual world...

    class parent

    {

    virtual void Show(){

    cout

  • 8/4/2019 c Interview Qsns

    25/31

    SRAVANICHOWDARY.B

    25

    class Boo{

    void foo() = 0;

    }

    Boo MyBoo; // compilation error

    What is Memory alignment??

    The term alignment primarily means the tendency of an address pointer value to be a multiple of

    some power of two. So a pointer with two byte alignment has a zero in the least significant bit.

    And a pointer with four byte alignment has a zero in both the two least significant bits. And soon. More alignment means a longer sequence of zero bits in the lowest bits of a pointer.

    What problem does the namespace feature solve?

    Multiple providers of libraries might use common global identifiers causing a name collisionwhen an application tries to link with two or more such libraries. The namespace feature

    surrounds a library's external declarations with a unique namespace that eliminates the potentialfor those collisions.

    namespace [identifier] { namespace-body }

    A namespace declaration identifies and assigns a name to a declarative region.The identifier in a namespace declaration must be unique in the declarative region in which it is

    used. The identifier is the name of the namespace and is used to reference its members.

    What is the use of 'using' declaration?

    A using declaration makes it possible to use a name from a namespace without the scopeoperator.

    What is an Iterator class?

    A class that is used to traverse through the objects maintained by a container class. There are fivecategories of iterators: input iterators, output iterators, forward iterators, bidirectional iterators,

    random access. An iterator is an entity that gives access to the contents of a container object

    without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time

    basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (asin array indices) or according to some ordering relation (as in an ordered binary tree). The

    iterator is a construct, which provides an interface that, when called, yields either the next

    element in the container, or some value denoting the fact that there are no more elements toexamine. Iterators hide the details of access to and update of the elements of a container class.

    Something like a pointer.

  • 8/4/2019 c Interview Qsns

    26/31

    SRAVANICHOWDARY.B

    26

    What is a dangling pointer?

    A dangling pointer arises when you use the address of an object after its lifetime is over. This

    may occur in situations like returning addresses of the automatic variables from a function orusing the address of the memory block after it is freed.

    What do you mean by Stack unwinding?

    It is a process during exception handling when the destructor is called for all local objects in thestack between the place where the exception was thrown and where it is caught.

    Name the operators that cannot be overloaded??

    sizeof, ., .*, .->, ::, ?:

    What is a container class? What are the types of container classes?

    A container class is a class that is used to hold objects in memory or external storage. A

    container class acts as a generic holder. A container class has a predefined behavior and a well-

    known interface. A container class is a supporting class whose purpose is to hide the topologyused for maintaining the list of objects in memory. When a container class contains a group of

    mixed objects, the container is called a heterogeneous container; when the container is holding a

    group of objects that are all the same, the container is called a homogeneous container.

    What is inline function??

    The __inline keyword tells the compiler to substitute the code within the function definition for

    every instance of a function call. However, substitution occurs only at the compiler's discretion.For example, the compiler does not inline a function if its address is taken or if it is too large to

    inline.

    What is overloading??

    With the C++ language, you can overload functions and operators. Overloading is the practice of

    supplying more than one definition for a given function name in the same scope.

    - Any two functions in a set of overloaded functions must have different argument lists.

    - Overloading functions with argument lists of the same types, based on return type alone, is an

    error.

    What is Overriding?

    To override a method, a subclass of the class that originally declared the method must declare a

    method with the same name, return type (or a subclass of that return type), and same parameterlist.

    The definition of the method overriding is:

  • 8/4/2019 c Interview Qsns

    27/31

    SRAVANICHOWDARY.B

    27

    Must have same method name. Must have same data type.

    Must have same argument list.

    Overriding a method means that replacing a method functionality in child class. To implyoverriding functionality we need parent and child classes. In the child class you define the same

    method signature as one defined in the parent class.

    What is "this" pointer?

    The this pointer is a pointer accessible only within the member functions of a class, struct, orunion type. It points to the object for which the member function is called. Static member

    functions do not have a this pointer.

    When a nonstatic member function is called for an object, the address of the object is passed as a

    hidden argument to the function. For example, the following function call

    myDate.setMonth( 3 );

    can be interpreted this way:

    setMonth( &myDate, 3 );

    The object's address is available from within the member function as the this pointer. It is legal,

    though unnecessary, to use the this pointer when referring to members of the class.

    What happens when you make call "delete this;" ??

    The code has two built-in pitfalls. First, if it executes in a member function for an extern, static,or automatic object, the program will probably crash as soon as the delete statement executes.

    There is no portable way for an object to tell that it was instantiated on the heap, so the classcannot assert that its object is properly instantiated. Second, when an object commits suicide this

    way, the using program might not know about its demise. As far as the instantiating program is

    concerned, the object remains in scope and continues to exist even though the object did itself in.Subsequent dereferencing of the pointer can and usually does lead to disaster.

    You should never do this. Since compiler does not know whether the object was allocated on thestack or on the heap, "delete this" could cause a disaster.

    How virtual functions are implemented C++?

    Virtual functions are implemented using a table of function pointers, called the vtable. There is

    one entry in the table per virtual function in the class. This table is created by the constructor ofthe class. When a derived class is constructed, its base class is constructed first which creates the

    vtable. If the derived class overrides any of the base classes virtual functions, those entries in the

    vtable are overwritten by the derived class constructor. This is why you should never call virtualfunctions from a constructor: because the vtable entries for the object may not have been set up

  • 8/4/2019 c Interview Qsns

    28/31

    SRAVANICHOWDARY.B

    28

    by the derived class constructor yet, so you might end up calling base class implementations ofthose virtual functions

    What is name mangling in C++??

    The process of encoding the parameter types with the function/method name into a unique nameis called name mangling. The inverse process is called demangling.

    For example Foo::bar(int, long) const is mangled as `bar__C3Fooil'.For a constructor, the method name is left out. That is Foo::Foo(int, long) const is mangled as

    `__C3Fooil'.

    What is the difference between a pointer and a reference?

    A reference must always refer to some object and, therefore, must always be initialized; pointersdo not have such restrictions. A pointer can be reassigned to point to different objects while a

    reference always refers to an object with which it was initialized.

    How are prefix and postfix versions of operator++() differentiated?

    The postfix version of operator++() has a dummy parameter of type int. The prefix version does

    not have dummy parameter.

    What is the difference between const char *myPointer and char *const myPointer?

    Const char *myPointer is a non constant pointer to constant data; while char *const myPointer isa constant pointer to non constant data.

    How can I handle a constructor that fails?

    throw an exception. Constructors don't have a return type, so it's not possible to use return codes.

    The best way to signal constructor failure is therefore to throw an exception.

    How can I handle a destructor that fails?

    Write a message to a log-file. But do not throw an exception.The C++ rule is that you must never throw an exception from a destructor that is being called

    during the "stack unwinding" process of another exception. For example, if someone says throw

    Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch(Foo e) { will get popped. This is called stack unwinding.

    During stack unwinding, all the local objects in all those stack frames are destructed. If one ofthose destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a

    no-win situation: should it ignore the Bar and end up in the } catch (Foo e) { where it was

    originally headed? Should it ignore the Foo and look for a } catch (Bar e) { handler? There is nogood answer -- either choice loses information.

  • 8/4/2019 c Interview Qsns

    29/31

    SRAVANICHOWDARY.B

    29

    So the C++ language guarantees that it will call terminate() at this point, and terminate() kills theprocess. Bang you're dead.

    What is Virtual Destructor?

    Using virtual destructors, you can destroy objects without knowing their type - the correctdestructor for the object is invoked using the virtual function mechanism. Note that destructorscan also be declared as pure virtual functions for abstract classes.

    if someone will derive from your class, and if someone will say "new Derived", where "Derived"

    is derived from your class, and if someone will say delete p, where the actual object's type is

    "Derived" but the pointer p's type is your class.

    Can you think of a situation where your program would crash without reaching the

    breakpoint which you set at the beginning of main()?

    C++ allows for dynamic initialization of global variables before main() is invoked. It is possiblethat initialization of global will invoke some function. If this function crashes the crash will

    occur before main() is entered.

    Name two cases where you MUST use initialization list as opposed to assignment in

    constructors.

    Both non-static const data members and reference data members cannot be assigned values;instead, you should use initialization list to initialize them.

    Can you overload a function based only on whether a parameter is a value or a reference?

    No. Passing by value and by reference looks identical to the caller.

    What are the differences between a C++ struct and C++ class?

    The default member and base class access specifiers are different.

    The C++ struct has all the features of the class. The only differences are that a struct defaults to

    public member access and public base class inheritance, and a class defaults to the private access

    specifier and private base class inheritance.

    What does extern "C" int func(int *, Foo) accomplish?

    It will turn off "name mangling" for func so that one can link to code compiled by a C compiler.

    How do you access the static member of a class?

    ::

  • 8/4/2019 c Interview Qsns

    30/31

    SRAVANICHOWDARY.B

    30

    What is multiple inheritance(virtual inheritance)? What are its advantages and

    disadvantages?

    Multiple Inheritance is the process whereby a child can be derived from more than one parentclass. The advantage of multiple inheritance is that it allows a class to inherit the functionality of

    more than one base class thus allowing for modeling of complex relationships. The disadvantageof multiple inheritance is that it can lead to a lot of confusion(ambiguity) when two base classesimplement a method with the same name.

    What are the access privileges in C++? What is the default access level?

    The access privileges in C++ are private, public and protected. The default access level assignedto members of a class is private. Private members of a class are accessible only within the class

    and by friends of the class. Protected members are accessible by the class itself and it's sub-

    classes. Public members of a class can be accessed by anyone.

    What is a nested class? Why can it be useful?

    A nested class is a class enclosed within the scope of another class. For example:

    // Example 1: Nested class//

    class OuterClass

    {class NestedClass

    {

    // ...

    };// ...

    };

    Nested classes are useful for organizing code and controlling access and dependencies. Nested

    classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass ispublic then any code can name it as OuterClass::NestedClass. Often nested classes contain

    private implementation details, and are therefore made private; in Example 1, if NestedClass is

    private, then only OuterClass's members and friends can use NestedClass.

    When you instantiate as outer class, it won't instantiate inside class.

    What is a local class? Why can it be useful?

    local class is a class defined within the scope of a function -- any function, whether a member

    function or a free function. For example:

    // Example 2: Local class

    //

    int f()

  • 8/4/2019 c Interview Qsns

    31/31

    SRAVANICHOWDARY.B

    {class LocalClass

    {

    // ...};

    // ...};

    Like nested classes, local classes can be a useful tool for managing code dependencies.

    Can a copy constructor accept an object of the same class as parameter, instead of

    reference of the object?No. It is specified in the definition of the copy constructor itself. It should generate an error if aprogrammer specifies a copy constructor with a first argument that is an object and not a

    reference.