Home > other >  How to split a vector into three variables in C
How to split a vector into three variables in C

Time:10-14

In Python the following expression splits the list a into the three variables x,y,z:

a = [2,5,7]
(x,y,z) = a

Is there anything similar in C ? I've tried writing the following code but it does not works:

#include <iostream>

int main() {
   int a[] = {3, 5, 7};
   int x,y,z;

   (x,y,z) = a;
}

Compiler fails with the following error:

error: assigning to 'int' from incompatible type 'int [3]'
    (x, y, z) = arr;

CodePudding user response:

You can use structured bindings starting from C 17, like so:

std::tuple<int, int, int> a{ 1, 2, 3  };

auto [x, y, z] = a;

See: https://en.cppreference.com/w/cpp/language/structured_binding

Pre-C 17 you can use std::tie, like so:

std::tuple<int, int, int> a{ 1, 2, 3  };

int x, y, z;
std::tie(x, y, z) = a;

See https://en.cppreference.com/w/cpp/utility/tuple/tie

If it has to be something other than std::tuple or std::pair, you'll have to assign the variables manually:

x = a[0]; y = a[1]; x = a[2];

CodePudding user response:

The following works (C 17 ):

int main() {
    int a[] = {3, 5, 7};
    auto [x, y, z] = a;
}

This will create copies of the values; to create references instead, use

auto& [x, y, z] = a;

CodePudding user response:

I always have a slight issue with "I come from programming language X and I want to do the same in language Y". Each language has different philosophies and you would do well to understand those. C is typed, has a lot of compile time checking and its very important to understand scopes and their influence on lifetime of objects (when are destructors called). So my advice is : if you want to do C learn C and kind of forget how you did things in Python

Having said that:

#include <iostream>

// best be explicit, define your own type! (or use one from a library)
struct vec_t
{
    int x;
    int y;
    int z;
};

int main()
{
    vec_t vec{ 1,2,3 };

    // no need to split, you can be explicit    
    std::cout << vec.x << "\n";
    std::cout << vec.y << "\n";
    std::cout << vec.z << "\n";

    // or you can use named bindings, but gain is minimal imo
    auto [x, y, z] = vec;

    std::cout << x << "\n";
    std::cout << y << "\n";
    std::cout << z << "\n";

    return 0;
}
  •  Tags:  
  • c
  • Related