This document contains a summary of a lecture on C++ functions:
- It discusses function parameters, return types, and calling functions. It provides an example function that prints the "99 bottles" song lyrics.
- Debugging functions using an IDE like Qt Creator is explained. The importance of function declaration order is also covered.
- Pre-written math functions from the <cmath> library are introduced as an alternative to writing functions like square root from scratch.
Presentation with a brief history of C, C++ and their ancestors along with an introduction to latest version C++11 and futures such as C++17. The presentation covers applications that use C++, C++11 compilers such as LLVM/Clang, some of the new language features in C++11 and C++17 and examples of modern idioms such as the new form compressions, initializer lists, lambdas, compile time type identification, improved memory management and improved standard library (threads, math, random, chrono, etc). (less == more) || (more == more)
If your concepts for C++ are weak then have a look at this
this will help you to know some concepts.If Any query plz tell me about C++ .
Also check my last uploads
and Please Do follow
How to make a large C++-code base manageablecorehard_by
My talk will cover how to work with a large C++ code base professionally. How to write code for debuggability, how to work effectively even due the long C++ compilation times, how and why to utilize the STL algorithms, how and why to keep interfaces clean. In addition, general convenience methods like making wrappers to make the code less error prone (for example ranged integers, listeners, concurrent values). Also a little bit about common architecture patterns to avoid (virtual classes), and patterns to encourage (pure functions), and how std::function/lambda functions can be used to make virtual classes copyable.
Presentation with a brief history of C, C++ and their ancestors along with an introduction to latest version C++11 and futures such as C++17. The presentation covers applications that use C++, C++11 compilers such as LLVM/Clang, some of the new language features in C++11 and C++17 and examples of modern idioms such as the new form compressions, initializer lists, lambdas, compile time type identification, improved memory management and improved standard library (threads, math, random, chrono, etc). (less == more) || (more == more)
If your concepts for C++ are weak then have a look at this
this will help you to know some concepts.If Any query plz tell me about C++ .
Also check my last uploads
and Please Do follow
How to make a large C++-code base manageablecorehard_by
My talk will cover how to work with a large C++ code base professionally. How to write code for debuggability, how to work effectively even due the long C++ compilation times, how and why to utilize the STL algorithms, how and why to keep interfaces clean. In addition, general convenience methods like making wrappers to make the code less error prone (for example ranged integers, listeners, concurrent values). Also a little bit about common architecture patterns to avoid (virtual classes), and patterns to encourage (pure functions), and how std::function/lambda functions can be used to make virtual classes copyable.
A glimpse at some of the new features for the C++ programming languages that will be introduced by the upcoming C++17 Standard.
This talk was given at the Munich C++ User Group Meetup.
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
The slides from the C++ and OOPS Crash Course conducted for ACM DBIT by Grejo Joby.
Learn the concepts of OOPS and C++ Programming in the shortest time with these notes.
Download this Presentation for free from www.ecti.co.in/downloads.html
No SIGN UP REQUIRED.
C++ Programming Training PPTs / PDFs for free.
Download free C++ Programming study material. Learn C++ Programming for free in 2 hours.
C# ist eine Programmiersprache mehrerer Paradigmen. C# war nie rein objektorientiert, schon in der ersten Version als Component-basierte Sprache angepriesen. Mit der Zeit gab es Erweiterungen der deklarativen Programmierung, und auch funktionale Konzepte wurden bei C# übernommen. In welche Richtung entwickelt sich C# weiter? In dieser Session werden neueste Erweiterungen von C# gezeigt. Themen sind dabei die letzten aktuellen Änderungen sowie geplante Erweiterungen wie z. B. die Vermeidung von NullReferenceException mit Non-Nullable Reference Types und die Reduktion von Garbage-Collector-Aufrufen mit Hilfe von Memory-Optimierungen.
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
I create the PVS-Studio analyzer detecting errors in source code of C/C++/C++0x software. So I have to review a large amount of source code of various applications where we detected suspicious code fragments with the help of PVS-Studio. I have collected a lot of examples demonstrating that an error occurred because of copying and modifying a code fragment. Of course, it has been known for a long time that using Copy-Paste in programming is a bad thing. But let's try to investigate this problem closely instead of limiting ourselves to just saying "do not copy the code".
PostgreSQL as seen by Rubyists (Kaigi on Rails 2022)Андрей Новиков
PostgreSQL has become the most popular RDBMS in the Ruby ecosystem in the last decade. It has a great set of built-in features, including a variety of versatile data types, both common and very specific.
But when we load data from the database to our application code, we're working with Ruby data types: classes from the standard library, Rails, or other gems. So while they can seem to be the same as their PostgreSQL counterparts, they are not absolutely identical, and sometimes that could lead to surprising behavior.
In this talk, I would like to explore the power of data types in PostgreSQL and Ruby and how to work with them properly to use both Ruby and PostgreSQL on 100% of their power!
Of complicacy of programming, or won't C# save us?PVS-Studio
Programming is hard. I hope no one would argue that. But the topic of new programming languages, or more exactly, search of a "silver bullet" is always highly popular with software developers. The most "trendy" topic currently is superiority of one programming language over the other. For instance, C# is "cooler" than C++. Although holy wars are not the reason why I'm writing this post, still it is a "sore subject" for me. Oh, come on, C#/lisp/F#/Haskell/... won't let you write a smart application that would interact with the outer world and that's all. All the elegance will disappear as soon as you decide to write some real soft and not a sample "in itself".
A C++ program //include headers; these are modules that include functions that you may use in your //program; we will almost always need to include the header that // defines cin and cout; the header is called iostream.h #include <iostream.h>
int main() {
//variable declaration //read values input from user //computation and print output to user return 0; }
After you write a C++ program you compile it; that is, you run a program called compiler that checks whether the program follows the C++ syntax – if it finds errors, it lists them – If there are no errors, it translates the C++ program into a program in machine language which you can execute.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
A glimpse at some of the new features for the C++ programming languages that will be introduced by the upcoming C++17 Standard.
This talk was given at the Munich C++ User Group Meetup.
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
The slides from the C++ and OOPS Crash Course conducted for ACM DBIT by Grejo Joby.
Learn the concepts of OOPS and C++ Programming in the shortest time with these notes.
Download this Presentation for free from www.ecti.co.in/downloads.html
No SIGN UP REQUIRED.
C++ Programming Training PPTs / PDFs for free.
Download free C++ Programming study material. Learn C++ Programming for free in 2 hours.
C# ist eine Programmiersprache mehrerer Paradigmen. C# war nie rein objektorientiert, schon in der ersten Version als Component-basierte Sprache angepriesen. Mit der Zeit gab es Erweiterungen der deklarativen Programmierung, und auch funktionale Konzepte wurden bei C# übernommen. In welche Richtung entwickelt sich C# weiter? In dieser Session werden neueste Erweiterungen von C# gezeigt. Themen sind dabei die letzten aktuellen Änderungen sowie geplante Erweiterungen wie z. B. die Vermeidung von NullReferenceException mit Non-Nullable Reference Types und die Reduktion von Garbage-Collector-Aufrufen mit Hilfe von Memory-Optimierungen.
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
I create the PVS-Studio analyzer detecting errors in source code of C/C++/C++0x software. So I have to review a large amount of source code of various applications where we detected suspicious code fragments with the help of PVS-Studio. I have collected a lot of examples demonstrating that an error occurred because of copying and modifying a code fragment. Of course, it has been known for a long time that using Copy-Paste in programming is a bad thing. But let's try to investigate this problem closely instead of limiting ourselves to just saying "do not copy the code".
PostgreSQL as seen by Rubyists (Kaigi on Rails 2022)Андрей Новиков
PostgreSQL has become the most popular RDBMS in the Ruby ecosystem in the last decade. It has a great set of built-in features, including a variety of versatile data types, both common and very specific.
But when we load data from the database to our application code, we're working with Ruby data types: classes from the standard library, Rails, or other gems. So while they can seem to be the same as their PostgreSQL counterparts, they are not absolutely identical, and sometimes that could lead to surprising behavior.
In this talk, I would like to explore the power of data types in PostgreSQL and Ruby and how to work with them properly to use both Ruby and PostgreSQL on 100% of their power!
Of complicacy of programming, or won't C# save us?PVS-Studio
Programming is hard. I hope no one would argue that. But the topic of new programming languages, or more exactly, search of a "silver bullet" is always highly popular with software developers. The most "trendy" topic currently is superiority of one programming language over the other. For instance, C# is "cooler" than C++. Although holy wars are not the reason why I'm writing this post, still it is a "sore subject" for me. Oh, come on, C#/lisp/F#/Haskell/... won't let you write a smart application that would interact with the outer world and that's all. All the elegance will disappear as soon as you decide to write some real soft and not a sample "in itself".
A C++ program //include headers; these are modules that include functions that you may use in your //program; we will almost always need to include the header that // defines cin and cout; the header is called iostream.h #include <iostream.h>
int main() {
//variable declaration //read values input from user //computation and print output to user return 0; }
After you write a C++ program you compile it; that is, you run a program called compiler that checks whether the program follows the C++ syntax – if it finds errors, it lists them – If there are no errors, it translates the C++ program into a program in machine language which you can execute.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
1. Wednesday, September 28, 2016
Programming Abstractions
Fall 2016
Stanford University
Computer Science Department
Lecturer: Chris Gregg
reading:
Programming Abstractions in C++, Chapters 2-3
CS 106B
Lecture 2: C++ Functions
parameters
function
result
2. Today's Topics
• Logistics:
• Signing up for section
• CS 106L
• Qt Creator installation help on Thursday
• Stanford Local Programming Contest: Saturday
• Homework 1: Fauxtoshop!
• Due Friday, October 7, at Noon
• A note on the honor code and cheating
• YEAH Hours tonight! (will be recorded!)
• Functions
• Some review — functions are very similar to Java functions!
• Value semantics
• Reference semantics
• Reading Assignment: Chapters 2 and 3
3. Logistics
•Signing up for section: you must put your available times by Sunday
October 2 at 5pm (opens Thursday at 5pm).
•Go to cs198.stanford.edu to sign up.
•CS 106L: A great opportunity to dig a bit deeper into "real" C++, and to see
interesting programming examples. Meets Tu/Th 1:30-2:50 in Hewlett 101.
•Qt Creator installation help: Thursday at 8pm, in Tressider (eating area).
Please attempt to install Qt Creator before you arrive (see the course website
for details).
•Remember, Assignment 0 is due Friday at Noon
•Stanford Local Programming Championship: Saturday:
cs.stanford.edu/group/acm/SLPC/
8. Fauxtoshop
•The program you write will utilize:
•Functions
•Constants
•Loops
•I/O (cout, getLine(), getInteger())
•Reference semantics, Value semantics
•Strings
•Logic
•Nicholas Cage
•We will discuss all of the above before the project is due
•Get started early! (Idea: finish Scatter by Friday!)
•Go to YEAH hours! Go to the LaIR!
•This is a non-pair programming program — you must work independently
•Due: 12pm (Noon) on Friday, October 7
10. Defining Functions (2.3)
A C++ function is like a Java method. Similar declaration syntax but
without the public or private keyword in front.
type functionName(type name, type name, ..., type name) {
statement;
statement;
...
statement;
return expression; // if return type is not void
}
return type parameters
Calling a function:
functionName(value, value, ..., value);
arguments (called in the same order as the parameters)
11. Function Return Types
A C++ function must have a return type, which can be any time (including
user-defined types, which we will cover later).
double square(double x); // returns a double
Vector<int> matrixMath(int x, int y); // returns a Vector
// probably not a good
// idea! (covered later)
string lowercase(string s); // returns a string (maybe
// not a good idea...
void printResult(Vector<int> &v); // returns nothing!
A C++ function can only return a single type, and if you want to return
multiple "things," you have to do it differently (unlike in languages
such as Python). We will cover this later, as well.
12. Function Example, brought to you by
#include <iostream>
#include "console.h"
using namespace std;
const string DRINK_TYPE = "Coke";
// Function Definition and Code
void bottles(int count) {
cout << count << " bottles of " << DRINK_TYPE << " on the wall." << endl;
cout << count << " bottles of " << DRINK_TYPE << "." << endl;
cout << "Take one down, pass it around, "
<< (count-1) << " bottles of " << DRINK_TYPE
<< " on the wall." << endl << endl;
}
int main() {
for (int i=99; i > 0; i--) {
bottles(i);
}
return 0;
}
(bus drivers hate them!)
13. Function Example: Output
99 bottles of Coke on the wall.
99 bottles of Coke.
Take one down, pass it around, 98 bottles of Coke on the wall.
98 bottles of Coke on the wall.
98 bottles of Coke.
Take one down, pass it around, 97 bottles of Coke on the wall.
97 bottles of Coke on the wall.
97 bottles of Coke.
Take one down, pass it around, 96 bottles of Coke on the wall.
...
3 bottles of Coke on the wall.
3 bottles of Coke.
Take one down, pass it around, 2 bottles of Coke on the wall.
2 bottles of Coke on the wall.
2 bottles of Coke.
Take one down, pass it around, 1 bottles of Coke on the wall.
1 bottles of Coke on the wall.
1 bottles of Coke.
Take one down, pass it around, 0 bottles of Coke on the wall.
14. Function Example, brought to you by
#include <iostream>
#include "console.h"
using namespace std;
const string DRINK_TYPE = "Coke";
// Function Definition and Code
void bottles(int count) {
cout << count << " bottles of " << DRINK_TYPE << " on the wall." << endl;
cout << count << " bottles of " << DRINK_TYPE << "." << endl;
cout << "Take one down, pass it around, "
<< (count-1) << " bottles of " << DRINK_TYPE
<< " on the wall." << endl << endl;
}
int main() {
for (int i=99; i > 0; i--) {
bottles(i);
}
return 0;
}
(bus drivers hate them!)
How many functions does this program have?
What does the bottles() function return?
Answer: 2. bottles() and main()
Answer: nothing (void function)
15. Function Example, brought to you by
#include <iostream>
#include "console.h"
using namespace std;
const string DRINK_TYPE = "Coke";
// Function Definition and Code
void bottles(int count) {
cout << count << " bottles of " << DRINK_TYPE << " on the wall." << endl;
cout << count << " bottles of " << DRINK_TYPE << "." << endl;
cout << "Take one down, pass it around, "
<< (count-1) << " bottles of " << DRINK_TYPE
<< " on the wall." << endl << endl;
}
int main() {
for (int i=99; i > 0; i--) {
bottles(i);
}
return 0;
}
(bus drivers hate them!)
Why is it a good idea to make DRINK_TYPE a constant?
Answer: So we can change it to Pepsi if we are
masochists. (actual answer: it allows us to make
one change that affects many places in the code)
16. Function Example 2
// Function example #2: returning values
#include <iostream>
#include "console.h"
using namespace std;
int larger(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
// Returns the larger of the two values.
int main() {
int bigger1 = larger(17, 42); // call the function
int bigger2 = larger(29, -3); // call the function again
int biggest = larger(bigger1, bigger2);
cout << "The biggest is " << biggest << "!!" << endl;
return 0;
}
17. Function Example 2
// Function example #2: returning values
#include <iostream>
#include "console.h"
using namespace std;
int larger(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
// Returns the larger of the two values.
int main() {
int bigger1 = larger(17, 42); // call the function
int bigger2 = larger(29, -3); // call the function again
int biggest = larger(bigger1, bigger2);
cout << "The biggest is " << biggest << "!!" << endl;
return 0;
}
Output:
18. Function Example 2: Debugging
•One of the most powerful features of an Integrated Development Environment
(IDE) like Qt Creator is the built-in debugger.
•You can stop the program's execution at any point and look at exactly what is
going on under the covers!
•In your program, click to the left of a line of code (line 18 below, for example)
•When you run the program in Debug mode (the green triangle with the bug on it),
the program will stop at that point. Let's see this in action!
19. Function Example 2: Debugging
•Notes from live debugging:
•You can see variable values as the program executes
•You use the following buttons to continue the program:
continue
to next
breakpoint
stop
running
Go to next
line but not
into functions
Go to next
line and
into
functions
Finish the
function
and leave
it
•Debugging effectively takes a little time to learn, but is super effective if you
have hard to find bugs.
20. Declaration Order
#include <iostream>
#include "console.h"
using namespace std;
const string DRINK_TYPE = "Coke";
int main() {
for (int i=99; i > 0; i--) {
bottles(i);
}
return 0;
}
// Function Definition and Code
void bottles(int count) {
cout << count << " bottles of " << DRINK_TYPE << " on the wall." << endl;
cout << count << " bottles of " << DRINK_TYPE << "." << endl;
cout << "Take one down, pass it around, "
<< (count-1) << " bottles of " << DRINK_TYPE
<< " on the wall." << endl << endl;
}
•Believe it or not, this program does not compile!
•In C++, functions must be declared somewhere
before they are used.
•But, we like to put our main() function first, because
it is better style.
21. Declaration Order
#include <iostream>
#include "console.h"
using namespace std;
const string DRINK_TYPE = "Coke";
// Function Definition
void bottles(int count);
int main() {
for (int i=99; i > 0; i--) {
bottles(i);
}
return 0;
}
// Function Code
void bottles(int count) {
cout << count << " bottles of " << DRINK_TYPE << " on the wall." << endl;
cout << count << " bottles of " << DRINK_TYPE << "." << endl;
cout << "Take one down, pass it around, "
<< (count-1) << " bottles of " << DRINK_TYPE
<< " on the wall." << endl << endl;
}
•Believe it or not, this program does not compile!
•In C++, functions must be declared somewhere
before they are used.
•But, we like to put our main() function first, because
it is better style.
•What we can do is define the function (called a
"function prototype") without its body, and that tells
the compiler about the function "signature" and the
compiler is happy.
22. C++ Pre-written Functions
•You have written a lot of functions before. What if we
wanted to find the square root of a number?
•We could manually write out a function (remember
Newton’s Method??) -- see the textbook!
•But, this would be counterproductive, and many math
functions have already been coded (and coded well!)
•The <cmath> library already has lots and lots of math
functions that you can use (you can go look up the code!
Actually...it's complicated -- see https://goo.gl/Y9Y55w if
you are brave. It is most likely true that the square root
function is built into your computer's processor, so there
isn't any readable code)
23. <cmath> functions (2.1)
#include <cmath>
Function Description (returns)
abs(value) absolute value
ceil(value) rounds up
floor(value) rounds down
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
pow(base, exp) base to the exp power
round(value) nearest whole number
sqrt(value) square root
sin(value)
cos(value)
tan(value)
sine/cosine/tangent of an
angle in radians
•unlike in Java, you don't write Math. in front of the function name
•see Stanford "gmath.h" library for additional math functionality
24. Value semantics
•value semantics: In Java and C++, when variables (int, double) are
passed as parameters, their values are copied.
•Modifying the parameter will not affect the variable passed in.
void grow(int age) {
age = age + 1;
cout << "grow age is " << age << endl;
}
int main() {
int age = 20;
cout << "main age is " << age << endl;
grow(age);
cout << "main age is " << age << endl;
return 0;
}
Output:
main age is 20
grow age is 21
main age is 20
25. Reference semantics (2.5)
•reference semantics: In C++, if you declare a parameter with an & after its
type, instead of passing a copy of its value, it will link the caller and callee
functions to the same variable in memory.
•Modifying the parameter will affect the variable passed in.
void grow(int &age) {
age = age + 1;
cout << "grow age is " << age << endl;
}
int main() {
int age = 20;
cout << "main age is " << age << endl;
grow(age);
cout << "main age is " << age << endl;
return 0;
}
Output:
main age is 20
grow age is 21
main age is 21
26. Reference semantics (2.5)
•Notes about references:
•References are super important when dealing with objects that have a lot of
elements (Vectors, for instance). Because the reference does not copy the
structure, it is fast. You don't want to transfer millions of elements between
two functions if you can help it!
•The reference syntax can be confusing, as the "&" (ampersand) character is
also used to specify the address of a variable or object. The & is only used
as a reference parameter in the function declaration, not when you call the
function:
void grow(int &age) {
age = age + 1;
cout << "grow age is "
<< age << endl;
}
yes!
int main() {
grow(age);
grow(&age);
return 0;
}
yes!
no!
27. Reference pros/cons
•benefits of reference parameters:
•a useful way to be able to 'return' more than one value
•often used with objects, to avoid making bulky copies when passing
•downsides of reference parameters:
•hard to tell from call whether it is ref; can't tell if it will be changed
foo(a, b, c); // will foo change a, b, or c? :-/
•(very) slightly slower than value parameters
•can't pass a literal value to a ref parameter
grow(39); // error
28. Reference Example
•Without references, you can't write a swap function to swap two integers. This is
true about Java. What happens with the following function?
/*
* Attempts to place a's value into b and vice versa.
*/
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
•Answer: the original variables are unchanged, because they are passed as copies
(values)!
29. Reference Example
•With references, you can write a swap function to swap two integers, because you
can access the original variables:
/*
* Places a's value into b and vice versa.
*/
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
•Answer: the original variables are changed, because they are passed as
references !
30. Tricky Reference Mystery Example
What is the output of this code? Talk to your neighbor!
void mystery(int& b, int c, int& a) {
a++;
b--;
c += a;
}
int main() {
int a = 5;
int b = 2;
int c = 8;
mystery(c, a, b);
cout << a << " " << b << " " << c << endl;
return 0;
}
// A. 5 2 8
// B. 5 3 7
// C. 6 1 8
// D. 61 13
// E. other
Note: please don't obfuscate your code like this! :(
See the International Obfuscated C Contest for much, much worse examples
31. Tricky Reference Mystery Example
What is the output of this code?
void mystery(int& b, int c, int& a) {
a++;
b--;
c += a;
}
int main() {
int a = 5;
int b = 2;
int c = 8;
mystery(c, a, b);
cout << a << " " << b << " " << c << endl;
return 0;
}
// A. 5 2 8
// B. 5 3 7
// C. 6 1 8
// D. 61 13
// E. other
Note: please don't obfuscate your code like this! :(
See the International Obfuscated C Contest for much, much worse examples
32. Quadratic Exercise -- how do you return multiple things?
•A quadratic equation for variable x is one of the form:
ax2 + bx +c = 0, for some numbers a, b, and c.
•The two roots of a quadratic equation can be found using
the quadratic formula at right.
•Example: The roots of x2-3x-4=0 are x=4 and x=-1
•How would we write a function named quadratic to solve quadratic equations?
•What parameters should it accept?
•Which parameters should be passed by value, and which by reference?
•What, if anything, should it return?
•We have choices!
33. Quadratic Exercise -- how do you return multiple things?
/*
* Solves a quadratic equation ax^2 + bx + c = 0,
* storing the results in output parameters root1 and root2.
* Assumes that the given equation has two real roots.
*/
void quadratic(double a, double b, double c,
double& root1, double& root2) {
double d = sqrt(b * b - 4 * a * c);
root1 = (-b + d) / (2 * a);
root2 = (-b - d) / (2 * a);
}
•How are we "returning" the results? Answer: by reference
•What other choices could we have made? Talk to your neighbor!
34. Quadratic Exercise -- how do you return multiple things?
•Possible choices:
•We could have returned a boolean if the roots were imaginary
•We could have added extra parameters to support some form of
imaginary numbers
•We could have called an error function inside this function (but that is not
always a good idea -- functions like this should generally have an
interface through the parameters and/or return value, and should
gracefully fail)
•We could have re-written the function as two functions that
return either the positive or negative root, without using
references.
•We could have returned a Vector<double> object (tricky syntax!)
35. Recap
•Fauxtoshop is out — start early!
•There are plenty of opportunities to get help before the deadline next Friday!
•Functions are to C++ as methods are to Java (and very, very similar)
•The Qt Creator debugger can show you real-time details of what your
program is doing, and it will come in super handy when you are trying to find
tricky bugs in your code.
•You must declare function prototypes before using them in C++!
•There are lots of pre-written functions (e.g., <cmath> and the Stanford
Library functions) that have been written already. Use them!
•Value semantics: pass by "value" means that you get a copy of a variable,
not the original!
•Reference semantics: using the & in a parameter definition will give the
function access to the original variable. This can be tricky until you get used
to it.
36. References and Advanced Reading
•References (in general, not the C++ references!):
•Textbook Chapters 2 and 3
•<cmath> functions: http://en.cppreference.com/w/cpp/header/cmath
•Obfuscated C contest: http://www.ioccc.org
•Code from class: see class website (https://cs106b.stanford.edu)
•Advanced Reading:
•Wikipedia article on C++ References: https://en.wikipedia.org/wiki/
Reference_(C%2B%2B)
•More information on C++ references: http://www.learncpp.com/cpp-tutorial/611-
references/
•C++ Newton's Method question on StackOverflow: http://
codereview.stackexchange.com/questions/43456/square-root-approximation-with-
newtons-method
•If you are super-brave, look at the square root C++ function in the C library: http://
osxr.org:8080/glibc/source/sysdeps/ieee754/dbl-64/e_sqrt.c?v=glibc-2.14#0048