Sunday, 17 March 2019

A Function with Constant Arguments C++

IN C++, an argument to a function can be declared as const as shown below. The argument with constant value should be initialized during the function declaration.

int strlen(const char *p);
int length(const string *s);

The qualifier const tells the compiler that the function should not modify the argument. The compiler will generate a error when this condition is violated. This type of declaration is significant only when we pass arguments by reference or pointers.

By a constant argument, it means that the function cannot modify the argument. If you pass a constant value to the function, then the function cannot modify the value as the value is constant. For example see the following sample program:

int len(const char[]);
int len(const char str[])
{
str[1]=str[1]+32;
return(strlen(str));
}
void main()
{
int k=0;
k=len("My String");
cout<<"Length of the string = "< getch();

On compiling the above program you will get the error message as – “Cannot modify a const object”. Because I am trying to modify the value of a constant argument in the line str[1]=str[1]+32; ( Trying to add 32 with the character at the index 1 of the character array str). Thus we have seen that const qualifier in function prototype and so in definition, tell the compiler that the function should not modify the argument. The constant arguments are useful when the functions are called by reference.

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top