CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15
  1. #1
    Join Date
    Sep 2016
    Posts
    22

    Question Function with input but no output?

    Hello!

    This function is supposed to have input but no output. I really want to understand how this works. Can someone help me fill in the gaps?

    Code:
    #include <iostream>
    
    using namespace std;
    
    void Hello(char* name)
    {
        cout << "Hello " << name << "!";
    }
    
    int main()
    {
        Hello("John");
        cin.get();
        return 0;
    }
    So the void means the function has no return. Hello is the name of the function. I'm not sure about that part in the parenthesis.

    As far as I know char is a character type and it can store a single character (letter), and char* indicates a character pointer which is a type of variable that can reference memory addresses of other variables.

    What type is name? Is it a char variable? Is it a char pointer? Maybe char vector? This I don't understand. I think it's a char pointer. But I can't see how it all fits in the big picture. Where or how is "John" stored? Is it stored at all?

    The Hello("John") is a function call, passing in "John" as a string literal and the only argument. As I said this is where I get stuck. What happens to "John"? Is it stored in name? Before it's printed out?

    I'm having hard time with this one. I hope someone can help me understand this.

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,398

    Re: Function with input but no output?

    Quote Originally Posted by cozySam View Post
    Hello!

    This function is supposed to have input but no output. I really want to understand how this works. Can someone help me fill in the gaps?

    Code:
    #include <iostream>
    
    using namespace std;
    
    void Hello(char* name)
    {
        cout << "Hello " << name << "!";
    }
    
    int main()
    {
        Hello("John");
        cin.get();
        return 0;
    }
    What type is name? Is it a char variable? Is it a char pointer? Maybe char vector? This I don't understand. I think it's a char pointer.
    As you can see from the function definition the type of name is char* - it is a char pointer. Or you can treat it as a character array.
    Victor Nijegorodov

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: Function with input but no output?

    char* indicates a character pointer which is a type of variable that can reference memory addresses of other variables.
    char* is a pointer (ie contains the memory address of) to a section of memory that contains data of type char (usually 1 byte).

    What happens to "John"? Is it stored in name? Before it's printed out?
    John is a string literal which the compiler stores in memory at some address chosen by the compiler. In Hello(), the parameter name is a memory address and is set by the compiler to the start of the memory address where the compiler stored the characters John. This is called a c-style string and in memory the chars are terminated by the null character (\0) to indicate the end of the string - often referred to as a null-terminated string.

    cout has name as a parameter for insertion to the stream. As name is of type char*, the characters stored in memory pointed to by name are sent to cout until a null terminator (\0) is found.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  4. #4
    Join Date
    Sep 2016
    Posts
    22

    Re: Function with input but no output?

    Alright, so name is a char pointer. And where is it pointing to? Where is the char that cahr* points to?

    Why is there no char declaration?

  5. #5
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,398

    Re: Function with input but no output?

    Quote Originally Posted by cozySam View Post
    Alright, so name is a char pointer. And where is it pointing to? Where is the char that cahr* points to?
    In the memory beginning with the address name. And there may be more than one char. All of them are between the address name and the address where the NULL character is.

    Quote Originally Posted by cozySam View Post
    Why is there no char declaration?
    Sorry. I don't understand what you mean here...
    Victor Nijegorodov

  6. #6
    Join Date
    Sep 2016
    Posts
    22

    Re: Function with input but no output?

    Quote Originally Posted by VictorN View Post
    In the memory beginning with the address name. And there may be more than one char. All of them are between the address name and the address where the NULL character is.

    Sorry. I don't understand what you mean here...
    Let me quote 2kaud here, maybe you will see what I mean.

  7. #7
    Join Date
    Sep 2016
    Posts
    22

    Re: Function with input but no output?

    Quote Originally Posted by 2kaud View Post
    char* is a pointer (ie contains the memory address of) to a section of memory that contains data of type char (usually 1 byte).

    John is a string literal which the compiler stores in memory at some address chosen by the compiler.
    This is also the confusing part for me. How does the compiler store the literal "John" in memory? As a char vector? So this is why I don't have to declare a new char vector e.g. char nameVector[]; and assign its address to the char pointer name using the & (address of) operator, e.g. name = &nameVector. The compiler does this automatically in the background?

    Quote Originally Posted by 2kaud View Post
    In Hello(), the parameter name is a memory address
    So name is a pointer to the memory location where the compiler auto-created the char vector (nameVector) and stored each individual letter of "John" in?

    Quote Originally Posted by 2kaud View Post
    and is set by the compiler to the start of the memory address where the compiler stored the characters John.
    This is a range of addresses. If "John" is stored as a vector then it will be stored as "J"+"o"+"h"+"n" which is concatenated to "John"? And char pointer name points to the first address in this range. (Also called the offset?)

    Quote Originally Posted by 2kaud View Post
    This is called a c-style string and in memory the chars are terminated by the null character (\0) to indicate the end of the string - often referred to as a null-terminated string.
    Meaning that the pure C language does not support strings the same way C++ or Java does? It breaks it up into individual characters (e.g. "J"+"o"+"h"+"n") and stores each character as a char in a char vector?

    Quote Originally Posted by 2kaud View Post
    cout has name as a parameter for insertion to the stream.
    A parameter?... if it can take parameters, does that mean that cout is a function or a method? I have not studied object orientation yet, but judging by what I know so far things like cout are part of the standard library and they are often objects of classes, and methods is the name for functions that an object can have inside a class. (Correct me if I'm wrong.)

    Quote Originally Posted by 2kaud View Post
    As name is of type char*, the characters stored in memory pointed to by name are sent to cout until a null terminator (\0) is found.
    The null terminator is automatically appended to the char vector (nameVector) by the compiler?

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: Function with input but no output?

    Please don't use the phrase char vector. In c++ this means something specific in a different context.

    To store the literal John in memory, the compiler generates code that asks the OS for the address of memory that can be used to stored 5 characters (J o h n \0). The code then copies these characters sequentially into memory starting at the memory address provided by the OS.

    The language c was developed before c++. null-terminated strings are part of the c language. c++ originally was based upon c so these null-terminated (c-style strings) can be used with c++. c++ also has a class called string which is the preferred way of using strings in c++. In c++ just referring to string would usually mean referring to the c++ string class. That's why when null-terminated strings are used in c++ they are often referred to as c-style strings (with a type char*).

    Consider cout to be an instance of a class. The operator << is overloaded for the class to mean insertion into the class - insertion into the cout class instance means display. Consider
    Code:
    cout << 123;
    This displays 123. This is actually
    Code:
    cout.operator<<(123);
    where 123 is the parameter for the class function operator<<.
    Last edited by 2kaud; September 30th, 2016 at 12:25 PM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  9. #9
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: Function with input but no output?

    How are you learning c++? Do you have a previous programming background?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  10. #10
    Join Date
    Sep 2016
    Posts
    22

    Re: Function with input but no output?

    Alright, so this is what I think might be going on.

    This is what the address range for the char vector nameVector might be and what the values might be.

    Code:
    Address     Value
    =================
    0x0f31      J
    0x0f32      o
    0x0f33      h
    0x0f34      n
    0x0f35      NUL
    This is what the variable values might be.

    Code:
    Variable    Type    Address     Value
    ======================================
    name        char*   0x0fb20     0x0f31
    nameVector  char    0x0f31      John
    As you can see the value of the char pointer name is the starting address of the nameVector. It references the first element in the vector.

    (I realize now that I may be using the term vector wrong here. You might want to replace that with array.)

  11. #11
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Function with input but no output?

    In C, there really is no such thing as a string variable type. What you're dealing with is the way the C language handles strings. I'd recommend reading up on how they work. This looks like as good a start as any

    http://www.programiz.com/c-programming/c-strings

  12. #12
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: Function with input but no output?

    IMO you're getting too involved with trying to understand some of the low level detail when with c++ it's the high level stuff that you should really be trying to understand. The c++ way for the program in post #1 could be
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    void Hello(const string& name)
    {
    	cout << "Hello " << name << "!\n";
    }
    
    int main()
    {
    	Hello("John");
    	cin.get();
    	return 0;
    }
    and not a pointer in sight! From where did the program in post #1 originate - if from an early part of a c++ course then I take issue with how they are teaching c++.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  13. #13
    Join Date
    Sep 2016
    Posts
    22

    Re: Function with input but no output?

    Quote Originally Posted by 2kaud View Post
    How are you learning c++? Do you have a previous programming background?
    I have learned some programming fundamentals on my own and I took a basic Python course before I started with this C++ course.

    Quote Originally Posted by 2kaud View Post
    From where did the program in post #1 originate - if from an early part of a c++ course then I take issue with how they are teaching c++.
    Yes, it's from the C++ course I'm taking. It's from the course book to be more precise, which is mandatory for the course by the way.

    How do you think I feel? I am relatively new to programming in general, and completely new to C++. I don't even have the basic knowledge to recognize the bad practices they are using. Bad teaching practices I should say. All I have is frustration!

    I now understand that my frustration stems not only from my inability to solve a computational problem using C++ but from the bad course plan and the bad book I'm reading. It's not because I'm dumb and don't have the will to learn, it's because it's taught to me in a wrong way. Frankly, if they are drilling down low level stuff like pointers and C style strings into my brain in a course titled C++ for beginners then I might as well go take a pure C programming course. That way I will at least have a decent understanding of what I just read, and take it with me as I move on to C++.

    The fact that it's a distance learning course doesn't help either. All I have is basically this stupid "mandatory" course book. I might have gotten better off reading some online tutorial than reading this book. But as it was said to be mandatory, because the course is based around the book, I thought I might as well stick to that. Besides, I'm almost done with it, so I don't want to jump to a web tutorial now and neither finish the book nor the tutorial before the course is over.

    Another thing that upsets me about this book is that the publisher is not making the code examples available for free download on their website. So every code example I find in the book I have to type in manually to test it. That's so time consuming! They only make the code examples available as downloads along with other so called teaching material for the special teacher's edition of the book. So that the teacher, who presumably already knows C++, can practice and learn even more C++ I guess! While I sit my *** off here and wear out my fingers while learning almost nothing. Honestly, most of the stuff I have read in this book I already knew. If it's anything I have learned here is that there are bad C++ books, and bad C++ teachers. (As if I didn't know that already! This just confirms it.)

    The guy who wrote this book is probably a very good and experienced programmer, but as a teacher or a book author... he sucks! I think he just wrote this book for some extra income. I have a very good reason to believe that. But I won't go any further on that. I have already said too much. I don't want this thread to turn into a book review, or a course review. There are simply good books and bad books, good courses and bad courses. This book and this course belongs to the latter category. Let's leave it at that.

    Quote Originally Posted by 2kaud View Post
    The c++ way for the program in post #1 could be

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    void Hello(const string& name)
    {
    	cout << "Hello " << name << "!\n";
    }
    
    int main()
    {
    	Hello("John");
    	cin.get();
    	return 0;
    }
    This code example looks much cleaner.

    I know I should probably Google this, but what is the keyword "const" used for? Something to do with constants I'm guessing? I have seen it used in at least 3 different code examples in the book I'm reading and not once has it been explained (unlike the other keywords which have been explained in some detail), and I have almost read the entire book now (unlikely it will be explained at the end of the book).

    The & is the "address of" operator? I read it can mean several things in different contexts. I have seen it used as "address of" for pointers and I have seen the double && as "and" operator in conditionals. I'm not sure how to read it in this case.
    Last edited by cozySam; October 2nd, 2016 at 06:17 AM.

  14. #14
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,398

    Re: Function with input but no output?

    Quote Originally Posted by cozySam View Post
    I know I should probably Google this, but what is the keyword "const" used for? Something to do with constants I'm guessing? I have seen it used in at least 3 different code examples in the book I'm reading and not once has it been explained (unlike the other keywords which have been explained in some detail), and I have almost read the entire book now (unlikely it will be explained at the end of the book).
    http://stackoverflow.com/questions/3...type-specifier
    Quote Originally Posted by cozySam View Post
    The & is the "address of" operator? I read it can mean several things in different contexts. I have seen it used as "address of" for pointers and I have seen the double && as "and" operator in conditionals. I'm not sure how to read it in this case.
    http://programmers.stackexchange.com...ific-functions
    http://stackoverflow.com/questions/6...ion-signatures
    Victor Nijegorodov

  15. #15
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: Function with input but no output?

    const basically means constant ie that the value can't be changed. Consider
    Code:
    int a = 4;
    ++a;
    a is now 5
    but
    Code:
    const int a = 4;
    ++a;
    gives an error as a is now a constant and can't have it's value changed. It's good programming practice to make variables const whenever possible to avoid programming errors (values being changed when they shouldn't be).

    & has several different meanings depending upon how its used. It can mean bitwise and, address of or reference. In this example it means reference. For functions, arguments can be passed either by value or by reference (there is also r-val reference but that's for advanced c++!). Without the & specified, the parameter is passed by value. This means that the specified variable in the function receives a copy of the value. Any changes to the variable in the function are not passed back to the calling function. If & is specified, then the parameter is passed by reference. This means that the specified variable in the function points to the same data as in the calling function and any changes to the variable are reflected back in the calling function. Consider
    Code:
    #include <iostream>
    using namespace std;
    
    void testv(int a)
    {
        ++a;
    }
    
    void testr(int& a)
    {
        ++a;
    }
    
    int main()
    {
        int x = 5;
        
        cout << "before testv x is " << x << endl;
        testv(x);
        cout << "after testv x is " << x << endl;
    
        testr(x);
        cout << "affer testr x is " << x << endl;
    }
    Because pass by value copies the variable, for some data types this can have a significant performance overhead. So the data is passed by reference even when it is not required or desired to change the value used in the calling function. So const is used so that if the value in the function is tried to be changed an error is generated.

    It's from the course book to be more precise, which is mandatory for the course by the way
    What book is this?

    For an on-line course in c++ have a look at
    http://www.learncpp.com/
    Last edited by 2kaud; October 2nd, 2016 at 07:13 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured