c++manipulators

C++ manipulators


I have started learning C++ and I think the language is great, but few things are baffling me while I am on my path learning it. In this example:

cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint);

In this example why do we type the whole setiosflags(ios::...) when the program still does the same if I only type showpoint without setiosflags?

Second question I have is simple. If we have the following:

int x=0;
cin>>x;

Why do we define a value for int if we later change it to something different than 0?


Solution

  • why do we type the wholesetiosflags(ios::...)when the program still does the same if I only type showpoint without setiosflags?

    We don't, unless we want the program to be more verbose than necessary. As you say, streaming setioflags with a single flag is equivalent to streaming the flag itself. You might use setioflags if you have a pre-computed set of flags you want to set.

    Why do we define a value for int if we later change it to something different than 0?

    Again, we don't, unless we like unnecessary verbiage. But it's a good habit to initialise variables, to avoid undefined behaviour if you later change the code to assume it has been initialised.