Need some help with some keywords

What does printf do differently than cout? Is printf considered C or C++? How could I use cout instead of print in this situation:

1
2
3
4
for( i=1; i<=t; i++ )
                        printf("%d ", numArray[i]);
			cout << "" << endl;
		}
Last edited on
Yeah, pretty much cout for C++ and printf for C. But there are subtle differences (cout is slightly faster, for example).

For your above code, you'd use cout like this:

1
2
3
4
5
cout << numArray[i];

// or

cout << numArray[i] << endl;


The endl example will add a newline character at the end.
Last edited on
printf() is a single function, whereas std::cout is a chain of functions. std::cout is a smart object - printf() isn't. printf() is used in C - std::cout is used in C++. And most importantly, std::cout is safer.

Wazzak
Last edited on
closed account (z05DSL3A)
I personally don't think that it helps to think of some parts of C++ as C and some parts not.

Yes, C has a printf() but so does C++!

1
2
3
4
5
6
7
8
#include <cstdio>

int main()
{
    printf("%d \n", 42);
    
    return 0;
}
NB: This will not compile with a C compiler only C++
NB: For some reason most C++ compilers let you get away without scope resolution here as it should be std::printf("%d \n", 42);
Last edited on
> Need some help with some keywords

Neither cout nor printf are keywords; they are just identifiers used by the standard library.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cstdio>

int main()
{
    int cout = 78 ;
    double printf = 23.92 ;
    std::cout << cout << ' ' << printf << '\n' ;
    std::printf( "%d %.2f\n", cout, printf ) ;
}

Topic archived. No new replies allowed.