doubt in c : Declaring variables in one line? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

11th Sep 2020, 3:38 PM
Monica
Monica - avatar
4 Answers
+ 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"
11th Sep 2020, 3:44 PM
Arsenic
Arsenic - avatar
+ 2
Arsenic is right 👍
11th Sep 2020, 3:46 PM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
+ 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 .
11th Sep 2020, 3:53 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 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...
11th Sep 2020, 3:45 PM
Jayakrishna 🇮🇳