C++ outline and interview questions (1): Variable

1.1. Contents

1.1.1Variable:

(1) Types: bool, char, int, long, longlong, float, double, long double.

(2) Range: 1 byte = 8 bits. - 1 bit, 7bits, 4 bytes, 4 bytes, 8 bytes, 4 bytes, 8 bytes, 8 bytes.

(3) unsigned: the unsigned version is usedfor taking the absolute value of a signed variable. It prevents the overflow.

(4) Initial value: for global/staticvariables, they are zero; for local ones, they are 0xccc (debug mode)/ a randomvalue (release mode).

(5) local/static/global: (Very important!)

(5.1)local variable: defined locally (isonly visible to certain functions, usu in a pair of curly braces); its valuestored in the stack of this function (i.e., the stack of this thread);disappear (its value will not be recovered) when the functioin ends; it hides a global variable of the same name(use scope resolution operator to distinguish them).

(5.2)global variable: defined globally(outside of any function, i.e. out of any pair of curly braces); local to thefile define them, and use extern to declare them in another file where they areused; they are initialized to be zero; they are stored in the global/staticstorage area (i.e., are visible to all threads of one process); will disappearwhen the program ends (i.e., the process terminates).

(5.3)static variable: has types ofvariables: local and global; combine the features of local and globalvariables; static local is only visible to the function where to declare themand initialized to be zero if not specific; static variable is stored in theglobal/static storage area, but they are not visible to other functions (i.e.,threads); their value will not disappear when the function ends (i.e., theirvalues will be same as that when the function ends, then they are used forrecord the system status, e.g., thetimes a function is called); static global variables are only visible tothefunctions declared in this file (i.e., cannot use extern to refer them inanother file, then from thisperspective, static and global are anonymous); static variable is used for decrease the coupling of functions anddependency on global variables (this can also simplify the design ofinterface).

(6)define/declare/refer:

(6.1)declare: set a name can be used byother variables or functions in the current file.

(6.2)define: declare and initialize avariable.

(6.3)refer: declare a variable which isdefined in some other source file.

2. Conversion:

(1) Implicit conversion is a typeconversion done by the compiler which is not intented by programmers; ithappens both in complilation time and runtime; implicit conversion is easy tocause ambiguities; use keyword “explict” to prevent this to happen (use itbefore the declaration of a function).

(2) Explicit conversioin is a name castwritten in code; they should return an lvalue;explicit conversions include:

(2.1)const_cast: add or remove const or volatileof a pointer, reference or a pointer toa pointer-to-data-member type. e.g.: const int *p_a = &a; int *b =const_cast<int *>(p_a); const int *c = const_cast<const int *>(b);this operator is usually used when a non-const parameter needs to be used as aparameter of another function which requires the inputs should be const.

(2.2)static_cast: undertakes the implicitconversion; it works like a C-style conversion:

(a) Can do: conversion between twoinner-defined types; conversion from a derived class to its base class (It is ILLEGLE to assign a base classinstance to a derived class instance!!!); convert pointers: from void * toa given type, from a derived class pointer/reference to its based class pointer/referenceand vise verse.

(b) Cannot do: convert from a struct/classto an inner type (this should use overloading conversion operator); cannotundertake the functions of const_cast; cannot convert between two irrelevanttypes.

(2.3)dynamic_cast: a safer conversionfrom a pointer or reference to a baseclass to that of its derived class (it gets same address with static_cast) orfrom one base class to another for multiple cases, i.e., safe downcasting; theinherence must be polymorphic, i.e., the base class or its derived class mustcontain at least one virtual function; safe conversion: return NULL when failto convert a pointer; throw a bad_cast exception when fail to convert areference.

(2.4)reinterpret_cast: rename a pointer(e.g., from int * to char *) or reference to an int/double/char;machine-dependancy; a C-style “polymorphiam”: get a void * by this operator andpass it as a parameter into a function where we can recover this cast back to avalid pointer of certain type.

3. Qualifiers:

Qualifiers will not distinguish overloadingdefinitions of a function.

(3.1)const: the variable that is confinedwill not change its value.

  consttype* / type const *: the value pointed by a pointer will not change.

  type*const: the value of a pointer (the address) will not change.

  consttype function(…): the return value is of the const type.

  typefunction(…) const: this function will not change the value of membersexcept they are mutable.

(3.2)volatile: Indicate a variable thatcan be changed by unexpected factors (i.e. other threads).

(3.3)mutable: Indicate a variable thatcan be changed by const member functions (i.e. type function(…) const).

(3.4)extern: describe a global variabledefined in another file to be used in the current file; it can also used as aquatifier of a function: extern “C” function_name(…); a programming trick: define a global variable in a .c/.cxx file anddeclare it by “extern” in the header file related with this file, which makesthis variable can be used in any file includes the header file.

Note: Use a pair of curly bracesfollowing extern “C” to declare multiple functions in C-style on time; thiswill be detailed explained in section 3; this keyword cannot be used withstatic: static implies a variable is only visible to the current file or function,which cannot be called from the outside.

4. Other structures: struct/enum/union/BOOL

(4.1)Struct: C-style and C++-style (classwith the visibility default to be public).

(4.2)Enum: used for setting aliases forevery status (numbers); this will make the code clear and easy to read. Thegeneral form is: enum Type {status_1 = 1, status_2, …, status_n, num_of_status}(Here is a good trick: add an extraname at the end of the enum which indicates the number of status we havedefined. It will increase by adding new status to the definition and the codewill not change).

(4.3)Union:

(4.4)BOOL: an old-fashioned type which isused to indicate error types or system status; its definition is: typedef intBOOL; It is different with bool in that it use 0 to indicate success andnon-zero integers to indicate system staturs after a function is called.

7. lvalue and rvalue

(7.1)lvalue – location value, a valuethat can get its address, e.g., m, ++i, the return value of a function returnby reference.

(7.2)rvalue – read value, a value thatcan read its value but cannot get its address, e.g., 3, 3 + 4, m + 5, thereturn value of a function return by value, i++.

Before C++ 11, we can only define areference to an lvalue.

1.2. Questions

Q: Isthere anything you can do in C that you cannot do in C++?

A: No. There is nothing you can doin C that you cannot do in C++. C++ is backward compatible with C.

Q: Whatare the differences between a struct in C and in C++?

A: Thedifferences can be summarized as follows:

(1) C supports only process-oriented programming paradiam, while C++ is a“mixed” language: it supports both process-oriented and object-oriented ones.

(2) C++ supports encapsulation, polymorphism and inherence at thelanguage level. C supports them at the “file” level and machine-dependent (i.e.,the implementation depends on the organization of files and conversion ofpointers between void * and other types):

(2.1) encapsulation in C: use the keyword static makes variablesand functions are only visible in the file where defined; use the keywordextern makes variables and functions can be called from another file.

(2.2) Polymorphism in C: use void * hide the difference ofparameter and function pointer to hide the details of function body.

(2.3) Inherence in C: define the collection of common features tobe a struct which will be defined in the struct which comes from it.

(3) Struct can be viewed as class with the visibility default tobe public. Everything thatapplies to class applies to struct.

(4) C++ add some newfeatures which make programming is safer: reference, new/delete and namecasting operators.

Q: Howmany ways are there to initialize an int with a constant?

A: (a) int foo = 123;

(b) int bar(123);

Q: How to compare a float/double variable with zero?

A: Givean error bound e (a very small float/double value) and use the form “x > (-1)* e && x < e”.

Q: How an int (long) / float (double) variable stored inmemory?

A: (1)int (long): stored in binary form; the first digit indicate the sign, if it isa signed value, otherwise, all positions are used to represent a number (therange also changes); it is accurately stored.

(2) float (double):stored in the form as follows: the first digit indicates sign, the following 8digits (11 digits for double) indicate the exponent, the remind digits are mantissa;it is scientific notation and so it is not accurate because it may be round-up.

Q: What the output of the following code: inti = 1; i++++;

A: i++ returns an rvalue (the currentvalue of i), which cannot be used in a post-increment. (++i)++ is correct.

Q: Whatare C++ storage classes?

A: Thestorage classes are as follows:

(1) auto: thedefault. Variables are automatically created and initialized when they aredefined and are destroyed at the end of the block containing their definition.They are not visible outside that block.

(2) register: a typeof auto variable. a suggestion to the compiler to use a CPU register for

performance.

Q: Whatare storage qualifiers in C++ ?

A: They are:

(1) const: indicatesa variable should not be altered by a program once initialized; it can bechanged unless it is changed by const_cast.

(2) volatile: indicatesa variable may be altered by unexpected factors (e.g., other threads); thiswill prevent the compiler to optimize this variable i.e., the compiler willread out its value from the memory but not the register area; volatile can beconst at the same time; volative * is legal, but volative *p_vol; *p_vol **p_vol may not be the square of a value pointed by p_vol (the value may bealtered).

(3) mutable:Iindicates that particular member of a structure or class can be altered evenif a particular structure variable, class, or class member function isconstant.

struct data
{
    char name[80];
    mutable doublesalary;
}
const data MyStruct= { "Satish Shetty", 1000 }; //initlized by complier
strcpy (MyStruct.name, "Shilpa Shetty"); // compiler error
MyStruct.salaray =2000 ; // complier is happy allowed
Q: How to refer a global variable?

A: There are two ways: (1)declare it in the current file by extern (2) include the header file whichdefines this variable. The difference is that the compiler will report errorwhen compile for the latter method, while the error will be reported in linkingperiod for the former method.

Q: Whether a global variable canbe defined in multiple .c files? Why?

A: Yes. Use extern to declarethem. This variable should be defined and initialized once. 


發佈了194 篇原創文章 · 獲贊 4 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章