-1

Is there a quick way to do the following without the repetition of i++

int i = 0;
printf("foo-%d,blah-%d,orange-%d", i++, i++, i++);

I need to do this with 8 or more pairs and the code looks horrible..

AlasdairC
  • 190
  • 1
  • 1
  • 14
  • 2
    Not only does it look horrible, it's undefined behavior. – Benjamin Lindley Sep 26 '12 at 16:41
  • You've got a whole lot of undefined behavior here. – Joe Sep 26 '12 at 16:41
  • Maybe you will need to create you own function in order to keep your code as clean as possible. Take a look at vprintf (http://www.manpagez.com/man/3/vprintf/) and variable arguments functions (http://stackoverflow.com/questions/1657883/variable-number-of-arguments-in-c) – Neozaru Sep 26 '12 at 16:48
  • One question under both [c++] and [printf] ... wow O_ó ... jsut to sound less obnoxious ... it's plain c, it should not be confused, even though it compiles. – luk32 Sep 26 '12 at 17:09
  • Why not `printf("foo-1,blah-2,orange-3");` or `int x = ...; printf("foo-%d,blah-%d,orange-%d", x, x + 1, x + 2);`? – PiotrNycz Sep 26 '12 at 21:39

3 Answers3

4

The order of evaluation of arguments is unspecified. Also, you can't modify a variable twice without an intervening sequence point. So do this instead:

printf("foo-%d,blah-%d,orange-%d", i, i+1, i+2);
i+=3;
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
3

Since you can have 8 or more pairs, I would like to suggest you to use a more readably and easy to extend version:

std::vector<std::string> vec_values = {"foo", "blah", "orange"};
for (size_t index = 0; index < vec_values.size(); ++index)
    std::cout << vec_values[index] << "-" << index;
Hugo Corrá
  • 14,546
  • 3
  • 27
  • 39
1

You might think of it in terms of the prefixes, not of the number:

int i = 0;
std::vector<std::string> prefixes { "foo", "bar", "baz", "ham" };

bool first = false;
for (const auto& prefix : prefixes) {
    if (!first)
        std::cout << ',';
    std::cout << prefix << '-' << i++;
    first = false;
}

If you can’t use C++11 range-based for, you can write it out in full:

for (auto prefix = prefixes.begin(); prefix != prefixes.end(); ++prefix) {
//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if (!first)
        std::cout << ',';
    std::cout << *prefix << '-' << i++;
    //           ~~~~~~~
    first = false;
}

Alternatively, use indices:

for (i = 0; i < prefixes.size(); ++i) {
//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if (!first)
        std::cout << ',';
    std::cout << prefixes[i] << '-' << i;
    //           ~~~~~~~~~~~           ~
    first = false;
}
Jon Purdy
  • 53,300
  • 8
  • 96
  • 166