When i declared some multiple random int variables in the C Programming Language.
CASE 1 : using int b=(20,30,400);
when i run the code with specifying round braces without declaring an array properly I'm getting output as 400
. Which is the last value in that.
#include <stdio.h>
int main() {
int b=(20,30,400);
printf("%d",b);
return 0;
}
CASE 2 : Using int b={20,30,400};
when i run the code with specifying curly-braces without declaring an array properly I'm getting output as 20
. Which is the first value in that.
#include <stdio.h>
int main() {
int b={20,30,400};
printf("%d",b);
return 0;
}
I wanted to know the exact working with braces in arrays, why it changing it output value.
In your first example you have this:
(20, 30, 40)
is an expression using the comma operator (twice). The comma operator evaluates the expression on the left-hand side, then the expression on the right-hand side, and has the value of the expression on the right-hand side. Therefore,(20,30,400)
"evaluates"20
and30
, then400
, and has the value400
. This is why the first code snippet prints400
.Your second code snippet does not seem to be valid C code to me. It compiles with warnings in gcc, even with
-pedantic
, so maybe I'm missing something. Best I can find in the current draft C23 standard at 6.7.10.12 is this:So I'd say the braces are ok, but you can't have more than one expression inside.