0

I am trying to print a comma-separated list of numbers by using a for loop, but I don't want there to be a comma after the last number, instead, I want there to be an endl.

I have this code:

for (int j = i; j > 0; j--) {
    // Should print 9, 8, 7, 6, 5, 4, 3, 2, 1[endl]
    cout << j << (j > 1 ? ", " : endl);
}

However, I get a compilation error

error: overloaded function with no contextual type information
    cout << j << (j > 1 ? ", " : endl);
                                 ^~~~

I have included iostream, endl works fine in other parts of the program, and replacing the endl with "\n" works fine...

I just want to know why this error occurs

  • 3
    The ternary operator is an *expression*. An expression must have a type which can be determined at compile time but in your case, the type depends on the result of this comparison which happens at runtime. It compiles fine with "\n" because then the return type is const char* irrespective of the result of this comparison. – lakshayg Oct 28 '18 at 19:25

3 Answers3

2

endl is a function that adds a \n and then flushes the stream, it's not a string. Hence you can't use it in a ternary with another string as they don't have the same type.

for (int j = i; j > 1; j--) {
    // Prints 9, 8, 7 ,6, 5, 4, 3, 2, 
    cout << j << ", ";
}
cout << 1 << endl;

Of course, you need to handle the case where i is smaller than 1.

The other option is to your "\n".

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
1

They must have the same type. Use "\n" instead.

for (int j = i; j > 0; j--) {
    // Should print 9, 8, 7, 6, 5, 4, 3, 2, 1[endl]
    cout << j << (j > 1 ? ", " : "\n");
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
1

Conditional operator ?:; can return only same type. endl is not the char* but "\n" is.

Andrey Sv
  • 247
  • 3
  • 6
  • 1
    Actually, the type of `”\n”` is neither of type `char*` nor convertible to this type! It is of type `char const[2]` which is convertible to `char const*`, though. – Dietmar Kühl Oct 28 '18 at 19:41
  • More precisely it type is 'const char*' an not is an array of char in classic meaning. And it can be convertable to 'char*' or void* or somethin else but cant be modified in runtime. – Andrey Sv Oct 28 '18 at 19:55
  • None of the above! If your compiler allows you to convert a string literal to `char*` it is non-conforming. The legacy conversion was deprecated right from the first standard and was removed from C++ with the C++14 revision (or C++17, not entirely sure when). ... and the type of string literals is definitely an array of `char const` objects! – Dietmar Kühl Oct 28 '18 at 19:59
  • Direct convertation as mentioned above will be to `const char*` but it can be like this in compiler C++17: `void* str = 1 > 0 ? (void*)"ssss" : (void*)"wefqwef";` and so on. – Andrey Sv Oct 28 '18 at 20:19