C++ Workshop - Functions, Parameters, & Scope (Ch. 5)

Started by
45 comments, last by me_minus 14 years, 7 months ago
I was wondering which of the next two code samples would be considered best.

int myFunction(int value1, bool value2 = true);int myFunction(int value1, bool value2) {   if(value2)   {      return value1 * 2;   }   return value1;}


int myFunction(int value1);int myFunction(int value1, bool value2);int myFunction(int value1) {   return myFunction(value1, true);}int myFunction(int value1, bool value2) {   if(value2)   {      return value1 * 2;   }   return value1;}


Since I am a Java programmer the second looks best to me (the first is not possible in Java). But I am wondering how a C++ programmer would look at this, is the usage of default values in your prototypes something that is commonly used?
Advertisement
Quote:Original post by RinusMaximus
I was wondering which of the next two code samples would be considered best.

[...]

Since I am a Java programmer the second looks best to me (the first is not possible in Java). But I am wondering how a C++ programmer would look at this, is the usage of default values in your prototypes something that is commonly used?

Since you are not adding logic in the one-parameter version, I would use the first form. That is what default parameters are for.
I have a question about page 101 at the bottom. It says that you can write your declarations in a file and include them. That would mean that you still have to write the definitions for it in the "main" file, doesn't it? Then why is it that cin and cout worked by just including iostream? can you write your definitions in that second file too?
If so, could I make a file "function" that has:

int addition(int a, int b)             {             return (a+b);             }


and a file "program" that has:

#include <iostream>#include <function>int main(){int a, b;std::cin >>a;std::cin >>b;std::cout << "/n the sum is: " << addition(a,b) << std::endl;return 0;}


I tried this before but it doesn't work...


EDIT: added tags
You made 2 tiny mistakes.

First of all it is recommended you save header files with a .h extention.
Eg: function.h


Next to include it:
#include "function.h"

Note that fuction.h should be saved in the same folder as main.cpp. Also you have to use double quotes to include your own files. <> are for standard header file ;)


Compleate Program
//------------------ function.h START ------------------int addition(int a, int b){   return (a+b);}//------------------ function.h END --------------------//------------------ main.cpp START ------------------#include <iostream>#include "function.h"int main(){  int a, b;  std::cin >>a;  std::cin >>b;  std::cout << "/n the sum is: " << addition(a,b) << std::endl;  return 0;}//------------------ main.cpp  END --------------------



You can also include .cpp files the same way. You can define your functions almost anywhere, as long as there is a declaration for that function before it is used
______________________________________________________________________________________________________
[AirBash.com]
Why do we need to use #inlcude function. We can do by defining function prototype as given in the book.

#include<iostream>int add(int a,int b); // function prototypeint main(){    int a,b;    using std::cout;    using std::cin;    cout<<"Enter the value of a and b:\n";    cin>>a;    cin>>b;    cout<<"the result is:"<< add(a,b);    char response;    cin>>response;    return 0;}


int add(int a,int b){    return(a+b);}


I have just now tried. This program is working for me.
hello any tutors i need help on workshop 1 nobody is helping me


grrrrrrrrrrr
Quote:Original post by NCLR
I have question in regarding c++.
iam trying to make a 'library' prog using a switch statement to do the following things :-
1) To enter books into library
2) To display them
3) To delete any one of them
4) To issue a book (just by asking the user various information such as name,library card number,book's name,author's name etc...)
5) To display them
6) To delete any one of them
7) Search for a book

Its a project which iam doing for school.
I used a class for enetring and displaying.Deleting i can do in 'void main()'.
i want these information saved "permenantly" in a file.But i dont how to that.
any suggesstions anyone?


Well, this definately is not the right place for the question. This chapter is about functions and we have not covered classes or file output yet. To get you started, look up the fstream header (specifically the ofstream object). They will let you write text to a file very easily. What you right and how you read it back is heavily dependant on your data.
Sean Henley [C++ Tutor]Rensselaer Polytechnic Institute
Quote:Original post by NCLR
I have question in regarding c++.
iam trying to make a 'library' prog using a switch statement to do the following things :-
1) To enter books into library
2) To display them
3) To delete any one of them
4) To issue a book (just by asking the user various information such as name,library card number,book's name,author's name etc...)
5) To display them
6) To delete any one of them
7) Search for a book

Its a project which iam doing for school.
I used a class for enetring and displaying.Deleting i can do in 'void main()'.
i want these information saved "permenantly" in a file.But i dont how to that.
any suggesstions anyone?


Quote:Original post by londonman
hello any tutors i need help on workshop 1 nobody is helping me


Uh... guys, there's sort of a set agenda in this thread :
kimi: It's so you can separate your code out into several files, for organizational purposes. (BTW, '#include' is not "a function"; it's a preprocessor directive.)

twoaterisn: Like FireNet said. Except, don't include .cpp files! You *can* include any kind of file, but it won't necessarily produce something that compiles ;)

You really want to read this on the subject of organizing source code files. But we should get back to functions, yes? :)

P.S. 'addition' sounds wrong as a function name. Consider either 'add' (imperative) or 'sum' (descriptive of the result, rather than the process).
Quote:Original post by Zahlman
P.S. 'addition' sounds wrong as a function name. Consider either 'add' (imperative) or 'sum' (descriptive of the result, rather than the process).


[OPTIONAL]
That's an interesting sentence, and this this chapter copes with function, I'd like to talk about function names.

A correct function naming scheme can save your (programmer) life. It will increase the code readability and will give hints about what the function does, and these are two good things. Of course, it is hard to describe what's a really good function naming scheme, but there are a few rules that can't be bad:
  • be descriptive and close to your subject: if the function is performing an addition, naming it do_something_with_two_integers() won't really help, unless do_something is a recognized idiomatic replacement for perform_an_addition. If your function's goal is to compute your debt rate, don't call it divide() (even if the forumla is, in the end, a simple division) but compute_debt_rate().

  • deal with the goal of your action, not the way you are doing it: the way you are doing things is called implementation details in our software design jargon. Implementation details might change, but the goal of the function is not likely to change. For example, find_substing_in_string() might be implemented using different algorithms, but the goal is still to find a substring in a bigger string.

  • use verbs when it make sense: most of the time, your function will perform an action. As a consequence, the imperative form is a good way to express the goal of this action - at least, it is better than a noun, because nouns describe things, not actions. Hence Zahlman's advice: use add() instead of addition().
    Of course, Zahlman is also true when it gives sum() as another possible name for addition(). Instead of using verbs, you may also be able to use nouns if this noun describe the result of the action (and not the action itself). For example, debt_rate() or position_of_substring_in_string() are good potential function names. However, this can only be true for functions that return something (let's be logic here: how can I describe the result of a function if the function don't have any result? it don't make much sense [smile])

  • sometimes, a verb is not enough: don't be afraid of putting a more detailed description in your function name. compute() is a little too simple, while compute_income() is more descritpive. In general, you should not be affraid of long function names, even if you should try to be concise (because very long function name (>60 char for example) are hard to read and can be a mess in your code). 30+ chars function names are not that ugly, and the editor you'll use is likely to support auto-completion (like VS2005 intellisense) which will ease typing.

Good function naming is hard to achieve - of course, experience might help in this area - but should definitely not be overlooked.
[/OPTIONAL]
Errata : p. 105 " Had you passed in widthOfYard, followed by lenghtOfYard, the FindArea() function would have used [...]"

The function is actually called Area() . I found some other typo like that in earlier chapters but didnt write them down.

Day 5 , exercice #3 p.135 : When calling myFunc() from the main function, the parameter used is (int). When calling a functions, parameters should be declared by name and not by type. If this is the case well, either the author wanted to call his int, int ( which is very confusing ) or its a typo. This exercice is a Bug Busters but this "error" isnt part of the answer in appendix D.

This topic is closed to new replies.

Advertisement