© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

7. What is the benefit of using const for declaring constants?

Ans:
The benefit of using the const keyword is that the compiler might be able to make optimizations based on the knowledge that the value of the variable will not change. In addition, the compiler will try to ensure that the values won’t be changed inadvertently.

Of course, the same benefits apply to #defined constants. The reason to use const rather than #define to define a constant is that a const variable can be of any type (such as a struct, which can’t be represented by a #defined constant). Also, because a const variable is a real variable, it has an address that can be used, if needed, and it resides in only one place in memory

Ex - 1: What is the output?

main()
{
unsigned char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}

Ans:
infinite loop

Explanation:
The difference between the previous question and this one is that the char is declared to be unsigned. So the i++ can never yield negative value and i>=0 never becomes false so that it can come out of the for loop.

Ex - 2: What is the output?
main()
{
char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}

Ans:
Behavior is implementation dependent.

Explanation:
The detail if the char is signed/unsigned by default is implementation dependent. If the implementation treats the char to be signed by default the program will print –128 and terminate. On the other hand if it considers char to be unsigned by default, it goes to infinite loop.
Rule:
You can write programs that have implementation dependent behavior. But dont write programs that depend on such behavior.

Ex - 3: What is the output?
{
int i=5;
printf("%d",++i++);
}

Ans:
Compiler error: Lvalue required in function main
Explanation:
++i yields an rvalue. For postfix ++ to operate an lvalue is required.


SLogix Student Projects
bottom