Home > OS >  assigning tuple to an int variable and printing the variable
assigning tuple to an int variable and printing the variable

Time:10-11

I tried assigning a tuple to an int variable. Here is my code. i = (12, 45, 58, -1, 90, 100); When I print i, it shows the value of 100. How does tuple work in C language ?

Thanks

CodePudding user response:

The right hand side expression is an expression with the comma operator

i = (12, 45, 58, -1, 90, 100);

Its value and the type is the value and the type of the last operand.

In fact the above statement is equivalent to

i = 100;

because other sub-expressions do not have a side effect.

From the C Standard (6.5.17 Comma operator)

2 The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

CodePudding user response:

In C, you can use structure as an alternative.

Sample code:

#include <stdio.h>
typedef struct
{
    int num1;
    int num2;
    char name[10];
}TupleInfo;

int main()
{
    TupleInfo tuple1 = {1, 2, "Marty"};
    printf("%d %d %s\n", tuple1.num1, tuple1.num2, tuple1.name);
    return 0;
}

Output:

1 2 Marty

Note: If you want to work with the similar data type, then using an array might be more convenient.

To learn more about structure in C, please check the following resources:

  • Related