How can I declare and define multiple variables in one line using C++?

后端 未结 10 1643
抹茶落季
抹茶落季 2020-11-27 11:09

I always though that if I declare these three variables that they will all have the value 0

int column, row, index = 0;

Bu

相关标签:
10条回答
  • 2020-11-27 11:54

    As of 2k18, you can use Structured Bindings:

    #include <iostream>
    #include <tuple>
    
    int main () 
    {
        auto [hello, world] = std::make_tuple("Hello ", "world!");
        std::cout << hello << world << std::endl;
        return 0;
    }
    

    Demo

    0 讨论(0)
  • 2020-11-27 11:58

    If you declare one variable/object per line not only does it solve this problem, but it makes the code clearer and prevents silly mistakes when declaring pointers.

    To directly answer your question though, you have to initialize each variable to 0 explicitly. int a = 0, b = 0, c = 0;.

    0 讨论(0)
  • 2020-11-27 12:01

    I wouldn't recommend this, but if you're really into it being one line and only writing 0 once, you can also do this:

    int row, column, index = row = column = 0;
    
    0 讨论(0)
  • 2020-11-27 12:04

    As @Josh said, the correct answer is:

    int column = 0,
        row = 0,
        index = 0;
    

    You'll need to watch out for the same thing with pointers. This:

    int* a, b, c;
    

    Is equivalent to:

    int *a;
    int b;
    int c;
    
    0 讨论(0)
提交回复
热议问题