C and C++ Tutorial

This is a guide for brushing up on concepts of C, C++, Object Oriented techniques and other gotchas that are commonly asked during programming interviews.
This tutorial follows an approach of questions and answers wherever possible that replicate common questions interviewers may ask. In cases where a code is necessary, I will write down few lines of code or attach a text file for you to download.


I put down this article together while I was preparing for my programming interviews. These are some of the questions that I encountered during my interviews or heard from people or read online. I hope this is helpful for you. Good Luck for your interview!


What is C? 
Developed by Dennis Ritchie, C was designed as an alternative to assembly language to write operating system utilities. Almost all firmware, modern operating systems and a great deal of application software is written in C. 


What is the difference between printf and fprintf? 

printf is used to display the output on the standard output. fprintf is used to display the output to whatever stream you specify it to. 

For eg: frpintf(stderr, "Hello, World" \n)'; displays the text Hello World in the standard error stream which is shown on the console. 


What is the difference between fgets and gets?

fgets: It is used to input data from the stream you specify it to. It takes in three arguements: a variable to hold data in, length of input data and the stream to pull data from.
 for eg; fgets ( char response, max_length, stdin);

gotcha: fgets reserves a byte for null terminator therefore it uses the length max_length - 1.


gets: It is similar to fgets but this function should never be used. It allows the user to type too much and crash the program. It was deprecated in C11. 


What happens in the following lines of code when the user types "Hi my name is XYZ"?

string response;
cin<< response;
cout>> "The string is" >> response;


gotcha: The following text is displayed: The string is Hi.

The complete text is not shown because cin is supposed to input only one word. Any space terminated words are truncated. To input the entire line, do the following:
getline(cin, response); 

What would happen if the following lines of code were executed?

int x= printf("Hello World!\n");
printf( %d, x);

It prints out 13.  This is so because printf printed out 13 characters.



What is static? What is auto? What is extern?
Concept of space allocation of variables in register:


auto is the default storage class. 

static does not go away. it stays static and does not get initialized everytime the function is called.

for eg: 

for( int i =0; i &lt;=5; i++)
{
     static int n=1;
     printf("number is %d", n++);

}


The output is :

number is 1
number is 2
number is 3 ... so on

extern  is used when we want to tell the compiler that I am going to use a function and this function is declared elsewhere in a file in the current folder. 




register is used to define variable that should be stored in the register. These variables will have maximum size equal to that of the register - typically 1 word..Registers dvariable stored in a register. memory, hence unary operator '&' cannot be applied to a o not have It should be noted that simply stating the variable as registered does not guarantee it will be stored in register, it depends on the hardware implementation of the machine. 


Pointers

int *ip; // pointer to an int

ip = &amp;x // ip stores the address of x

Arrays, Character Arrays and referencing using pointers
int ia[5];  // array of 5 int elements
int *ip = ia; // ip points to beginning of ia.
*ip = 2; // the first element of ia stores 2
++ip; // increment pointer to the next element;
*ip = 3; // store 5 in the element pointed to by ip.

gotcha: char array ends with a null character.
char s[] ="string" is same as char s[]= { 's','t,'r','i','n','g', 0};


Functions
gotcha: C is always pass by value. 
Preprocessors:


#define CONSTANT 1

#include // system level headers
#include "file.h"  // header files specific to a project


Macros:

#define MAX(a,b) ( a > b ? a : b) 

gothca: In evaluating an expression, the arguments are evaluated from right to left. So for eg:


int increment{
static int i=42;
i +=5;
printf("increment returns %d\n", i);
return i;
}


int main (int argc, char **argv) {

int x=50;
printf("max of %d and %d is %d \n", x, increment() , MAX(x, increment()));

return 0;


}
The output is: 

incremement returns 47
incremment returns 52
max of 50 and 52 is 50 

which is  incorrect.

this is happening because MAX() is being evaluated first, the left arguements (and functions) later.


line continuations: a "\" is a line continuation preprocesor. It helps to insert a new line in the code but tells the compiler that the line is actually being continued and the code is not broken.


So:

printf("This\
is\
a\
line");

w
ould output: This is a line
without any breaks.


Include once:

it is used to ensure that the compiler doesn't include same file multiple times. 
#ifndef  or #ifdef are used.
Eg:

#ifndef _INCLUDE_A

#define _INCLUDE_A

//some code


#endif



#pragma does the same trick. 


Data Type and size:


char :  1 byte
short int 2 byte
int 4 byte
long int 8 byte 

float: 4 byte
double float : 8 byte
long double float: 16 byte

char[] myString = "String";
// this looks like there are 6 characters, but in fact the length of the array is 7 bytes. This is because of the last null character in the string. 

Difference between C string and C++ string:

- C strings are fundamental type. but C++ string is a class from the Standard Template Library

- for C strings, the sizeof() operator would return the correct length. For C++, the string.size() would do. 

Type qualifiers:
const: immutable. value cannot be changed.
volatile: objects that can be changed by another process such as in multi-threaded programming
mutable: modfiy a data member from a const qualified member function. Only available in C++

Storage qualifiers:
static: stored in static memory.
extern: these variables are linked together at link time.
register: stored in process registers


C++ references:

int i =0;
int & ir= i ; //reference to i
ir = 15

// At the end of this code, the value of i = 15.


gotchas
-  For a reference, we do not need to write &ir = &i as we would in case of a pointer.
- There is no way to change a reference variable once it it set. It cannot be used to create an array of references and pointed to null unlike pointers.

Therefore, references whenever taken should always be used as a const. 


Struct and Class difference:

The data members default to private in class but in struct they are public.enum:
enum months { Jan, Feb, March, April};

Union: is a data structure that allows you to use the same memory space for different data types. 



Void pointer:
Used for pointers whose type is not known. 

Void pointers in C++ must be explicitly casted. 


Pointer to a function: 
for a function int f (int i) { }

the pointer is determined by:

int (*pFunc) (int) ; 

pFunc = &f;

so call the function through the pointer using int i = (*pFunc) (47)

Functions

In C and C++, all arguements are passed by value. Therefore  a copy of the variable is passed. 

gotchas: auto variables are stored on stack. static variables are stored on data segment of memory. dynamically allocated variables are stored on heap. 

Variable arguement functions:
In order to create a function that takes in multiple (unknown) parameters, the syntax to declare it is:

#include <stdarg.h>

double average(const int count, ...)
{
va_list ap;
int i;
double total = 0.0;

va_start(ap, count);
for(i = 0; i < count; i++) {
total += va_arg(ap, double);
}
va_end(ap);
return total / count;

}

The lines in bold are mandatory.

Classes and Objects:

Members of a class default to private as opposed to struct whose members default to public.

gotcha: in certain cases when a const variable is instantiated, the member functions that handle this variable must be const safe, ie. they should not accidentally attempt to modify the variable.

therefore, the following syntax should be followed:

int myClass::myGetter () const {
return member;
}


Class Constructors and Destructors

//Default Constructor:
Animal(): type("ABC") , sound("EFG);

//Constructor with arguements passed by reference.
Animal(const string & breed, const string & sound);

//Copy Constructor 
Animal (const Animal & a)

//Assignment operator
Animal & operator = (const Animal &o); 

//Destructor
~Animal();



gotchas:Once a destructor is called, the objects are deleted in reverse order. 
So, if Animal A, Animal B and Animal C are created in this order, once a destructor is called, the order of deletion is : C, B, A


New and DeleteFor every new, there must be a delete otherwise we will have memory leak problems.


InheritancePublic methods: base class, dervied class and all other objects can access.
Protected methods: only base class and derived class can access.
Private: only base class can access.

To make a class only available to dervied class, it is a good idea to make the constructors private and protected.






C++ syntax:
cin >> t;
initializing an array:
int myarray[size];




Difference between new and malloc()



1. new allocates continous space and malloc allocates distributed space.
2. memory must be allocated using sizeof() when malloc is used. But we do not need to allocate memory when new is used.
3. new initilizes memory to 0 but malloc gives random values.




Most of the material is from lynda.com's tutorial on C and C++. Click here to check out the original tutorial. 



No comments:

Post a Comment

Search This Blog