+ 1
doubt in c : Declaring variables in one line?
why should we not declare a variables like below? #include <stdio.h> int main() { [ int a, b, c = a+b; ] float salary = 56.23; char letter = 'Z'; a = 8; b = 34; printf("%d \n", c); printf("%f \n", salary); printf("%c \n", letter); return 0; } Output gives wrong ans like: 0 [ though ans is 42 ] 56.2300 Z Correct code: #include <stdio.h> int main() { int a, b; float salary = 56.23; char letter = 'Z'; a = 8; b = 34; int c = a+b; printf("%d \n", c); printf("%f \n", salary); printf("%c \n", letter); return 0; } Output: 42 56.2300 Z
4 Réponses
+ 3
This is because at the time of assigning the values of "a+b" to variable "c", there are no values(thus a garbage value) in variables "a" and "b" in the first code
whereas in the second one values of "a" and "b" were initialised before the statement "c=a+b"
+ 2
Arsenic is right 👍
+ 2
When you decleared variable c=a+b here you have not intilize the value of a and b so by default a and b are garbage or 0 and u adding both Values so result is 0 after that you initializing a=8 and b=34 it wont be add u already assigned a+b in c and c is procedural language so it wont be pass in a and b .
+ 1
You mean about the line
int a, b, c =a+b;
If yes, then a, b are not yet assigned any values,
(it is not works by references here, it is by values)..
So default values a=0,b=0 are assigning c=a+b=0,.. But you may get garbage values aslo...
Assignment happening to a, b after c=a+b;
If you add this after a, b assignment then c value change as you want as you doing it in 2nd program...
C evaluation of expressions are top to bottom... Line by line.. Sequential....
Hope it help...