Tokens | Subroutine | C++

Prof. Mr.Manoj.

Kavedia

The smallest individual units in a program are known as “Tokens”. There are different types of tokens: 1. Keywords 2. Identifiers 3. Constants 4. Strings 5. Operators 6. Literals Keywords Keywords are explicitly preserved identifiers and cannot be used as names for program variables. The below keywords underlined are the enhanced features of C. Asm Auto Break Case Catch Char Class Const Typedef continue default delete do double else enum extern float for new operator friend goto protected if public inline register int return long short signed sizeof private switch template this through try

Tokens, expressions and control structure tokens

1

static

Identifiers & Constants It can be designed as the name of variables and some other program elements using combination of characters A-Z, special characters and 0-9. The major difference between C & C++ identifiers is C++ has no limit on the length of the variable. Constants refer to fixed values that don’t change during the execution of the program. C & C++ supports kinds of literal constants that are int, char, floating that is literals. Example: const int a=10; It is a decimal int constant to declare a char constant. Const char a=’9’; Const char *b=”ABC”;

Void data type The type void was introduced for two uses 1. It specifies return type of function. 2. It indicates empty argument list to the function. Void function (void) Example : void empty (void)

Prof. Mr.Manoj. Kavedia

C++ void can be used as data type in the declaration of generic pointer. i.e. void *gp; A generic pointer can be assigned a pointer value of any basic data type but it may not be dereferenced. Example : void *gp; int *ip; Ip=gp; //invalid Gp=ip; //valid Because it would not make any sense to dereference the pointer a void pointer.

2

Enumerated data types This data type is another user defined, which provides a way for attaching names to numbers, thereby increasing readability of code. The enum keyword automatically enumerates a list of words by assigning them values 0, 1, and so on. The syntax is, Enum shape of {circle, ellipse} The enumerated data type slightly differs in C++ compared to C i.e. in C++ the tag’s name shape becomes new type, that means we can declare variable using tag names i.e. shape square. C defines enums to be integers. In C++ each enumerated data type retains its own separate type i.e. C++ doesn’t permit an integer value to be automatically converted to enum value. Example enum color{red, blue, green}; Color background= blue //valid in C++ Color back=1; //invalid in C++ By default enums are assigned integers values starting with 0 for first enum and so on. Another statement. Enum color { red, blue=5 }; and Enum color { red=4, blue }; In the first statement the value of red is 0 and in second the value of blue is 5. In the second case value of red is zero, blue is 7. Therefore green will be 7. C++ also permits following declaration: Enum {OFF, ON}; Where OFF=0; & ON=1 & can be referred as constant integers. Example int switch1=OFF; int switch2=ON; Operators In C++ C++ has a set of operators. All C operators are valid in C++ i.e. arithmetic operators, comparison operator , assignment operator, logical operator and bit wise logical operators. C++ has additional special operators 1. Scope resolution operator (::) 2. Pointer to member declaration (:: +) 3. Pointer to member operator (-> * %) 4. New operator (: -). This is used to allocate memory. 5. Delete operator. This operator is used to release memory. Scope resolution Blocks and scopes can be used in constructing program we know that some variable name can be used to have different meanings in different blocks. The scope of variable extends from the point of declaration till the end of use containing that declaration. example the variable x to two different memory locations containing values as shown below. { int x = 10; { int x = 20; }

Prof. Mr.Manoj. Kavedia

} The variable declared inside the block is said to be local to that block. In C, the global version of variable cannot be accessed within the inner block of local variable. But C++ resolves this problem by introducing new operator called as scope resolution operator. The general syntax of this operator is, :: varname. This operator allows the access global version of variable using the statement, :: x; The above statement means x is global version of variable & not the local. Int x=5; Void main() { int x=1; cout<<x; cout<<::x; }

3

//local //global

Output is 1 The second use of scope resolution operator is defining the member functions of class outside the class. Example. class xyz { public: void getd (); }; void xyz::getd() { }; Type cast operator C++ permits explicit type conversion of variables or expression using type cast operator. Syntax:- data type (expression/variable); Expression and implicit conversion An expression is combination of operators, constants and variables. Expressions are of 4 types: a)constant expression b)Integer expression Example: a+b where a & b are of type integers. c)float expression Eexample: a/b will always result in a float expression. wherever the data types are mixed in an expression. C++ performs implicit conversion automatically. The expression, is divided into sub expression consisting of one operator & two operands. If operands type differs the compiler converts one of them to match with other using certain rules i.e. smaller type is converted to the larger type. Example : int a; float b,c; c=a+b; as ‘a’ is a smaller data type. It is automatically converted to float data type. Operators precedence and association 1. Scope resolution operator (::) 2. Dot operator (.) 3. Increment & Decrement operator 4. Unary minus operator 5. New & Delete operator

Prof. Mr.Manoj. Kavedia

6. Its association is from right to left. 7. Pointer 8. Arithmetic operator a.*, /, % b.+, 9. Relational operator (<<, >>, <<=, >>=, = =, !=) 10. Bit wise operator 11. Logical operator 12. Ternary/Conditional operator 13.Assignment operator.

4

Functions in C++ Function prototype The prototype describes the function interface to compiler by giving details such as number and type of argument and type of return. When a function is called, the compiler uses the templates to ensure that proper arguments are passed. Any violation in the matching argument and the return type will be checked and controlled by compiler at the time of compilation. Function prototype is the statement declaration in the following program. The general syntax is , <data type> function name(arg/list) Eexample : float volume(int a, int b) In the function declaration, the names of variables are dummy variables and therefore they are optional. Call by reference In C, a function call passes the argument by value. The called function creates a new set of variables and copies the value of arguments to them. The function does not have access to actual program and can only work on copy values. But in C++ provision of reference variable permits to pass the arguments to the function by reference without pointers. When we pass arguments, the formal argument in the called program becomes synonymous to actual arguments. The concept of reference variable in C++ is that it provides an alternative name for previously defined variable. Example: if the variable sum is required to refer the variable. A reference variable is created by defining pointers in C language. Example: int total; int *sum; sum=&total; In C++ a reference variable is created using the syntax data type & ref var=var; The previous definition of C is rectified as, Int & sum=total; Where total is int type variable that has been already declared while sum is alternative name declared to represent the variable total. Both the variables refer to same data in same memory location.i.e. both the variables are synonymous. Any change made to one variable is function-passing arguments to function by reference. Considering the example of swapping two numbers. Code Using Pointer Void main() { int x=1,y=2; void swap(int *, int *) swap (&x, &y) cout<<x<<y; } void swap(int *a, int *b) { int temp; temp=*a;

Prof. Mr.Manoj. Kavedia

a=b; *b=temp;

5

} Code Using reference void main() { int x==1,y=2; void swap (int &, int &); swap (x, y); cout<<x<<y; } void swap (int &a, int &b) { int temp; temp=a; a=b; b=temp; } Return by reference A function can also return a reference. i.e. int & large (int &x, int &y) { if(x > y) return(x); else return(y); } Since the return type of maths function is int & it returns the reference of x or y but not the values of x &y. The maths function will return the reference of either a or b depending on their values. In the above example it returns the reference of b as b>a. the return by reference function can appear on left hand side of assignment statement. In above example it assigns –1 to either a or b depending on the number which is greater. Default argument C++ follows to call a function without specifying all the arguments. In such case, the function assigns default value to the parameter, which does not have matching argument in the function call. The default values are specified to the argument when the function is declared. Example. float amt(float p, float r, float y=10) { return (p*r*n)/100; } The default value is specified to the arguments & its subsequent function call is given as below. Float a=amt (500,0.12); In this function call the value of y is explicitly passed as 5. The default arguments are passed only from right to leave. The statement below is illegal statement. i.e. Float amt(float p, float r=0.12, float y) //illegal Inline functions One of the objectives using function in a program is to save memory space. When a function is likely to be called a number of times in the program, a lot of extra time in executing a series of instruction such as jumping to the function, saving registers, pushing arguments into the stack and returning to the calling function out . when a function is small, a substantial percentage of execution may be spent in such overheads. One solution to this problem may be to use macro definition known as the pre processor macro. The major

Prof. Mr.Manoj. Kavedia

drawback of macro is that they are not really function and therefore error checking does not occur at the time of compilation. C++ has different solutions i.e. a new feature called as inline function. This is a function expanded in one line and when it is invoked. In inline function the error checking is possible. It also has a return type. & the compiler replaces this function call with the corresponding function code instead of jumping to the function memory location. Syntax Inline <return type> function name (arg) { //function definition } example inline int cube(int r) { return(r*r*r); }

6

On execution of this statement the values of called program.i.e double c= cube (3); Every time when a function is called the value of ‘C’ is 27. It’s far superior to the micros. The benefits of inline function dimensions as the function grow inside that is if the statement definition is too long the compiler will treat as normal function. It may not work for the following expansion. 1. Functions returning values if the loop or goto exists. 2. If the function contains static variable. 3. If inline functions are recursive. Function overloading Over loading refers to the use of something for different purposes. C++ also allows overloading of the function i.e. we can create same function to perform the variety of different task. This is known as function overloading or function polymorphism. Using polymorphism concept in oops, we can design a family of functions with in function name, but with different argument list the correct function to be invoked is determined by checking a number and type of arguments but not as the function type. E.g. an overloaded add operation handles different data types of data as given below: Function declaration Int add (int a, int b); int add (int a , int b, int c); double add(float a, float b); Function call add (10,20); add(11.2,13.5); add(1,2,3); a function call first matches the prototype having same number and type of arguments and then calls the appropriate function for execution. In the above example the first function declaration the function selection involves the following steps. 1. Compiler tries to find an exact match in which the actual arguments are same and it uses that function. 2. If an exact match is not found, the compiler used the integral promotions to the actual arguments. e.g.: char to int float to double to find a month for a function call. 3. When either of them fails, the compiler tries to use built in function conversions to the actual arguments. If the conversion has multiple matches then the compiler will generate an error message. For example. Function declaration

Prof. Mr.Manoj. Kavedia

Long add (long a, long b); Double add(double a, double b); function call add(10,20); for the function call add(10,20) the complier generates an error message i.e. integer arguments can be converted to either long or double to both. They’re by creating a problem to compiler as to which function. 1. If all the steps fail, the tries user defined conversion in combination with integral promotion. 2. Perform arithmetic operations for two float variables using inline function. 3. Multiply two variables of different data types using function overloading. 4. Find volume of cube, cylinder & rectangle using function volume. Program #include<iostream.h> #include<conio.h> int volume(int); int volume(double, int); int volume(long, int, int); void main() { cout<<volume(20)<<”\n”; cout<<volume(8.5,10)<<”\n”; cout<<volume(100L,15,75)<<”\n”; return(); Function Overloading } int volume(int a) Allows a function z return(a*a*a); } To operate differently double volume(double r, int h) { Depending upon return(3.14*r*r*h); } The data types and.or no. long volume(int lint b, int h) { Of the argument passed to it. return(l*b*h); } Program #include<iostream.h> #include<conio.h> inline float add(float a, float b) { return(a+b); } inline float sub(float c, float d) { return(c-d); } inline float div(float e, float f) { return(e/f); } inline float mull(float g, float h) { return(g*h); } void main() {

7

Prof. Mr.Manoj. Kavedia

clrscr(); cout<<add(10,20); cout<<sub(20,10); cout<<div(10,2); cout<<mul(2,15); getch();

8

} Summary

Sign up to vote on this title
UsefulNot useful