+ 1

Need a little help in c

I have 3 programs.. First one: #include<stdio.h> int main() { int i = (5, 6, 7); printf("%d", i); return 0; } Answer to this question is 7 Second one: #include<stdio.h> int main() { int i = 5, 6, 7; printf("%d", i); return 0; } In this one compilation fails... Third one: #include<stdio.h> int main() { int i; i = 5, 6, 7; printf("%d", i); return 0; } In this answer is 5... Why?? All three of these are almost identical, yet different results..??

17th Jan 2018, 2:50 PM
Ayush walia
Ayush walia - avatar
2 Answers
+ 6
Normal usage of comma would be: int a=1,b=2,c=3; //defines 3 integers a, b, and c giving values of 1, 2, and 3 respectively second usage is: for (a=1,b=2;a<b;a++) f(a);//assigns 1 to a and 2 to b looping once In program 1, the parentheses separate the 3 expressions from the assignment. The result is the last expression of 7 which gets assigned to i. You could have used any valid expressions such as function calls or assignments. int i = (f(5),a=6,7); //also legal when f and a are defined prior to this statement In program 2, you are attempting to declare 6 and 7 as integers, which is illegal. Besides example above, you could use: int i=5,j,k=6,l,m=7; //Creates 5 integers In program 3, you have 3 valid expressions i=5 does your assignment. The values of the other two aren't used.
17th Jan 2018, 3:11 PM
John Wells
John Wells - avatar
+ 1
2nd you declared i=5 then you tried to declare 6 and 7 as variable and according to the rule you cannot declare number or special character as a variable 1st and 3rd i'm not sure what exactly happened
17th Jan 2018, 3:05 PM
‎ ‏‏‎Anonymous Guy