Here are a few C++ puzzles which are aimed at helping one in understanding C++ better.
1)Declaring a variable
const char *var1="String";
Which of the operations are valid on var1?
1)var1="Hello";
2)*var1='H';
Answer:
When var1 is declared as a const char *var1="String"; you are specifying var1 as pointer to a character constant i.e the contents of the location pointed by var1 are constant. So you can not change the contents of the location pointed to by *var1. The assignment *Var1='H' attempts to change the Content pointed by the pointer var1. But with the assignment var1="Hello"; the contents of location pointed by var1 is not changing but the var1 is made to point to a whole new location i.e location of String Hello.
2)Similar to above example
char* const var2 = "String";
1)var2="Hello"
2)*var2='H';
Now var2 is declared as a constant pointer to character. var2 always points to the same memory location. however the value held by the memory location can be updated. Hence the var2="Hello"; is wrong and *var2='H';
3) Will this program compile successfully ?
void f(){};
void g() {return f();}
main()
{
g();
}
Answer:
No.
void g() means that it can not return anything-not even a void value. Here return f() means it is trying to return void.
1)Declaring a variable
const char *var1="String";
Which of the operations are valid on var1?
1)var1="Hello";
2)*var1='H';
Answer:
When var1 is declared as a const char *var1="String"; you are specifying var1 as pointer to a character constant i.e the contents of the location pointed by var1 are constant. So you can not change the contents of the location pointed to by *var1. The assignment *Var1='H' attempts to change the Content pointed by the pointer var1. But with the assignment var1="Hello"; the contents of location pointed by var1 is not changing but the var1 is made to point to a whole new location i.e location of String Hello.
2)Similar to above example
char* const var2 = "String";
1)var2="Hello"
2)*var2='H';
Now var2 is declared as a constant pointer to character. var2 always points to the same memory location. however the value held by the memory location can be updated. Hence the var2="Hello"; is wrong and *var2='H';
3) Will this program compile successfully ?
void f(){};
void g() {return f();}
main()
{
g();
}
Answer:
No.
void g() means that it can not return anything-not even a void value. Here return f() means it is trying to return void.
No comments:
Post a Comment