1

big newbie here and just trying to intensely study each little bit of code i write to figure out why and how things are happening, as that's just how I learn best.

In an attempt to understand why and when to put variables inside a function's parameters rather than establishing them inside the function itself, I tried out the code below:

string dayOfWeek(){
    
    string dayName;
    int dayNum = 3;

    switch(dayNum){
            case 0:
        dayName = "Sunday";
        break;
            case 1:
        dayName = "Monday";
        break;
            case 2:
        dayName = "Tuesday";
        break;
            case 3:
        dayName = "Wednesday";
        break;
            case 4:
        dayName = "Thursday";
        break;
            case 5:
        dayName = "Friday";
        break;
            case 6:
        dayName = "Saturday";
        break;

            default:
                dayName = "invalid day number";


    }
    
 return dayName;

}
    

    
int main()
{


    cout << dayOfWeek;

    return 0;
}

I'm wondering why it prints 1? I am under the impression it should print "Wednesday", since I declared that dayNum = 3, and in the case of it being 3, it would mean that dayName = "Wednesday". Any pointers? Thanks.

Quack
  • 133
  • 7
  • 7
    `dayOfWeek` is a function name. If you use it this way it is not executed. Try `cout << dayOfWeek()`. – axiac Feb 17 '21 at 13:00
  • Surprised it prints 1. Would have thought it would print the address of the function dayOfWeek. – cup Feb 17 '21 at 13:04
  • 1
    Besides the question, I just noticed that you write `cout` instead of `std::cout` and `string` instead of `std::string`. You don't show it explicitly in your provided code, but I suspect you added `using namespace std;` somewhere. This is considered bad practice. For more information about this, see https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Brotcrunsher Feb 17 '21 at 13:35
  • @cup -- a pointer to **data** can decay to a `void*`, and there's a stream inserter for `void*` that displays the contents of the pointer, i.e., the address that it holds. `dayOfWeek` is a pointer to a **function**, and pointers to functions do not decay to `void*`. So the only applicable stream inserter is the one that takes `bool`, and the pointer is converted to `bool`. – Pete Becker Feb 17 '21 at 14:54

2 Answers2

4

You're printing out the function dayOfWeek itself, which decays to function pointer, and converts to bool with value true (as non-null function pointer), then gets printed as 1 (you can use std::boolalpha to print out bools as true or false, e.g. cout << std::boolalpha << dayOfWeek).

You should call the function as

cout << dayOfWeek();
//               ^^
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
3

In the main part, you should change this code; cout << dayOfWeek();// because you are calling the function, you should use ()

Ogün Birinci
  • 598
  • 3
  • 11