I am Not understanding why im getting output like this : Understanding Arrays

79 Views Asked by At

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.

1

There are 1 best solutions below

0
On

In your first example you have this:

    int b=(20,30,400);

(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 and 30, then 400, and has the value 400. This is why the first code snippet prints 400.

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:

The initializer for a scalar shall be a single expression, optionally enclosed in braces, or it shall be an empty initializer

So I'd say the braces are ok, but you can't have more than one expression inside.