
- Forum
- Programming Talk
- C and C++
- Is there any Difference
Is there any Difference
This is a discussion on Is there any Difference within the C and C++ forums, part of the Programming Talk category; Consider declaring variables and using then for computation in C++ program as below in Method 1 and Method 2 Method ...
-
Is there any Difference
Consider declaring variables and using then for computation in C++ program as below in Method 1 and Method 2
Method 1:
int a, b, c;
a=b+c;
Method 2:
int b, c;
int a=b+c;
Though on the user interface side both gives the same result I have a doubt in this. Is there any difference in the working of Method 1 and Method 2 internally or will it get assigned and evaluated internally also in the same way. Kindly explain me.
-
Yes there is clearly a distinction between the internal working of Method 1 and Method2.Methdo2 is always preferred than Method1 when you understand the internal working of both methods. In method1 the expression b+c is evaluated and is stored in a temporary object of type int and then only it is assigned to integer variable named as a. After assigning the value of b+c integer variable a, the temporary object gets destroyed. In contrast in method 2 the value of b+c is calculated and directly assigned to integer variable a without the use of temporary variable. So performance wise method2 is always better than method1.
-
Is there any difference - Yes there is...
Method 1:
int a, b, c;
a=b+c;
Method 2:
int b, c;
int a=b+c;
In the first case we are declaring 3 variables and next step we are adding two values and assigning it to 'a';
Whereas in the second case we are declaring two variables by name 'b' and 'c' and in the next step we are declaring a variable by name 'a' and immediately assigning sum of b and c. so we are minimizing the declaration line.
In the first case 3 variables are getting declared and then the expression.
I hope i have cleared your doubt.
Regards,
Gayatri
-
12-27-2010, 07:25 AM #4
- Join Date
- Dec 2010
- Answers
- 32
well all this doesn't mak any difference of the program in low level but it does makes difference at higher level...
in the 1st method b+c is calculated and stored in a but in between this calculation and setting the value of a, temporary object is created after the calculation and that object is usted to store the value in a where as in the 2nd method b+c is directly stored in a, here no object is created, hence the process time is less so it is much faster during the processing time......
-
Sponsored Ads

Reply With Quote





