Tell me how to work with such a three point in brackets. I need a function that summarizes an indefinite number of integers. You can use an example or a link to a normal resource.

---- UPDATED AFTER 2 COMMENTS --------

#include <iostream> using namespace std; void f(int a, ...){ int * p = &a; while (*p){ cout << *p << endl; p++; } } int main(){ f(1, 3, 56, 4); return 0; } 

---------------conclusion---------------------------------- ---

 1 3 56 4 22997204 30403626 2147303424 -858993460 -858993460 1245112 4305311 1 3430632 3421160 -1011716776 22997204 30403626 2147303424 -1302397296 

I do not understand where the garbage is taken from?

  • Such a thing is called the variadic function (the term varargs is most often used). Here several approaches are described, the most straightforward - sishny, s ++ - way is, as far as I understand, through the template. Well, and how it is written below - it will be quite correct to arrange this number of numbers as a vector. - etki
  • one
    [Here] [1], for example ____ @perfect, your example worked correctly for me (it started in VS 2013). What compiler do you use? [1]: rsdn.ru/forum/cpp/418970.1 - Donil
  • 3
    You just got lucky. The fact is that the arguments in this case will be located on the stack. But there are a lot of other things on the stack (for example, the return address of a function). The code in the question naively hopes that after the last argument in the stack will be 0. Yes, it can be, but no one guarantees this. But it will be much more fun if the argument list starts from 0. In this case, the function decides that there is absolutely nothing there. - KoVadim
  • @Donil vs 2010 under windows xp. @KoVadim are right. - perfect

1 answer 1

I have already told about garbage in the comment - during the execution there are no official ways to find out the number of arguments in the stack. But if you use a new standard (well, what a new one it is, it has been around for several years and is supported by all the adequate compilers) and slightly alter the syntax, then you can write this:

 #include <iostream> using namespace std; int summ(std::initializer_list<int> list) { int s = 0; for (int x: list) { s += x; } return s; } int main() { int a = summ({1,2,3,4}); cout << a << endl; return 0; } 

(you need to compile with the -std=c++0x key)

Additional braces are not so terrible, but they bring a lot of advantages. You can even write this func({1,2,3,4},{5,8,9}, "test"); - it is immediately clear that the function will accept two lists and a string (the function header will be such a void func(std::initializer_list<int> list1, std::initializer_list<int> list2, std::string s);

  • An interesting way, thanks. - perfect