Variables and Scope - CS50 Shorts
Key Takeaways
Explains variable scope in C, including local and global variables
Full Transcript
[Music] as you start working with functions another thing is gonna become really important to understand which is the concept of variable scope so scope is a characteristic of a variable that defines from which functions that variable can be accessed there are two primary scopes in C local variables and global variables now local variables can only be accessed within the functions in which they're created they can't be accessed by every other function that exists in your program only the function in which it was created global variables in other hand can be accessed by any function in the program and the reason for that is because they're not created inside of any particular function we declare them outside of all of the functions which means that every function knows where it is and can access and manipulate it so far in the course you've pretty much been working exclusively with local variables here's an example of a very very simple main function and a very simple additional function that we've written in this case X which I've colored green just to highlight the the locality of the scope of that variable is local to the function triple main cannot refer to X at all it doesn't know what it is no other function in fact if we had additional functions in here could refer to X similarly result which I've colored blue is local only two main only main knows what the variable result is triple cannot use it now as I mentioned global variables do exist if you declare that variable outside of any function all of the functions in the program can refer to it so in this case I've highlighted in green a global variable declaration in this case the variable being declared is called global to be extremely clear about it it is of type float and I assign it the value point 5050 you'll notice that in Maine and in triple I am able to refer to global and in fact if I go through the program as indicated main first calls triple triple multiplies global by three which has its value to one point five something find one point five one or something like that and then Maine also prints out the value of global so Maine will not print out point five oh five oh it will print out Global Times three one point five one so you got to be careful when you're working with global variables while they're very flexible and being able to pass information around so that every function can use it it also can have some dangerous consequences if one function changes the value of a variable before you expect it to be changed why does this distinction matter why do we care whether some variables are local and others are global well for the most part local variables in C are what's called passed by value when we make a function call what does that mean well when a variable is passed by value the call e which is another way of saying the function that is receiving the variable that gets passed in as an input it actually doesn't receive that variable itself it receives its own copy of it to work with this is a really important distinction we just saw a second ago that with global variables if we manipulate the global variable in one function its effect is that the effect in that one function carries through to every other function but with local variables that's not true each function when it receives variables as input receive copies of those variables not the variables themselves so what is the tied effect of that that means that the variable in the caller the function that is making the function call is unchanged unless you overwrite it for example in this code foo is not changed at all int foo equals for call triple of foo inside of triple we would expect that foody x three and returned but there's actually no effect here though a very subtle difference this does have the effect we want do you see why we're overriding foo in main this time so in through equals four foo equals triple foo when we make that call triple gets its own copy of foo its own copy of four it says return four times three or whatever variable gets passed in times 3 and then we assign the return value of triple to foo again so this actually would overwrite foo this is the only way to do this with local variables so now if we added another line of code here at the end of main to print out the value of foo it would in fact print out 12 variable scope can get is generally not too much of a problem if you name all of your variables different things but they can get kind of nasty if the same variable name appears in multiple functions which will happen a lot if you be if you ever do work in the real world where you are working on collaborative programs and people in different teams are working together to write the same program or the same set of programs they'll frequently reuse variable names particularly common ones like X Y IJ and so on but when variables have the same name scope issues can get a little trickier to parse for example do you know what will be printed out at the end of this particular program take a minute pause the video and read through this program you can see at the top we have a function declaration for a function called increment that function takes a single parameter an integer which we call X and it outputs an integer that's the return type at the beginning then we have main a couple of lines of code and main the last of which is a print statement and remember that's the that's the question here what is actually going to be printed at the end of this function and then we actually have the definition of increment below so take a minute step through the code trace things out do you know what will be printed at the end of this particular program all right hopefully you've taken a few seconds to try and parse this one out let's do it together so I've crossed out increment declaration at the top there was kind of a distraction it's not its own variable it's not doesn't have its own scope it's just a function declaration so for purposes of trying to parse out what's happening in this program we might as well just avoid it now we have in this case the reason this problem is tricky is because we have local variables in both main and increment each of which is called X and of course the crux of this issue is trying to suss out which X gets changed and how does it get changed so I've colored every instance of X that's local to Maine red and I've colored every instance of X that's local to increment blue notice in that third line of Maine y equals increment X that increment is not being passed Maine's X or the red X it's getting passed a copy of it and it's only going to work with that copy of it the blue X if you're mathematically inclined you might have instead thought of this as X sub M for Maine and X sub I for increment but it's the same idea X sub M or the red X's in the previous slide are the variables that are local is the instance of X rather that is local to Maine and X sub I or the blue variables in the previous slide are the instances of X that are local to increment so we were able to figure out what this function printed at the end I'm Doug Lloyd and this is cs50
Original Description
***
This is CS50, Harvard University's introduction to the intellectual enterprises of computer science and the art of programming.
***
HOW TO SUBSCRIBE
http://www.youtube.com/subscription_center?add_user=cs50tv
HOW TO TAKE CS50
edX: https://cs50.edx.org/
Harvard Extension School: https://cs50.harvard.edu/extension
Harvard Summer School: https://cs50.harvard.edu/summer
OpenCourseWare: https://cs50.harvard.edu/x
HOW TO JOIN CS50 COMMUNITIES
Discord: https://discord.gg/T8QZqRx
Ed: https://cs50.harvard.edu/x/ed
Facebook Group: https://www.facebook.com/groups/cs50/
Faceboook Page: https://www.facebook.com/cs50/
GitHub: https://github.com/cs50
Gitter: https://gitter.im/cs50/x
Instagram: https://instagram.com/cs50
LinkedIn Group: https://www.linkedin.com/groups/7437240/
LinkedIn Page: https://www.linkedin.com/school/cs50/
Reddit: https://www.reddit.com/r/cs50/
Quora: https://www.quora.com/topic/CS50
Slack: https://cs50.edx.org/slack
Snapchat: https://www.snapchat.com/add/cs50
Twitter: https://twitter.com/cs50
YouTube: http://www.youtube.com/cs50
HOW TO FOLLOW DAVID J. MALAN
Facebook: https://www.facebook.com/dmalan
GitHub: https://github.com/dmalan
Instagram: https://www.instagram.com/davidjmalan/
LinkedIn: https://www.linkedin.com/in/malan/
Quora: https://www.quora.com/profile/David-J-Malan
Twitter: https://twitter.com/davidjmalan
***
CS50 SHOP
https://cs50.harvardshop.com/
***
LICENSE
CC BY-NC-SA 4.0
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
https://creativecommons.org/licenses/by-nc-sa/4.0/
David J. Malan
https://cs.harvard.edu/malan
malan@harvard.edu
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from CS50 · CS50 · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Hello, World: Hadi Partovi
CS50
Content Distribution and Archival in a Digital Age
CS50
CS50 2014 - Week 1
CS50
CS50 2014 - Week 3
CS50
CS50 2014 - Week 0, continued
CS50
CS50 2014 - Week 4
CS50
Week 3, continued
CS50
Quiz 0 Review
CS50
CS50 2014 - Week 3, continued
CS50
CS50 2014 - Week 7
CS50
CS50 2014 - Week 7, continued
CS50
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
CS50 2014 - Week 9
CS50
How to Build Innovative Technologies by Abby Fichtner
CS50
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
CS50 2014 - Week 10
CS50
This is CS50 with Steve Ballmer?
CS50
Meteor: a better way to build apps by Roger Zurawicki
CS50
Data Analysis in R by Dustin Tran
CS50
Data Visualization and D3 by David Chouinard
CS50
CS50 2014 - Week 6
CS50
Build Tomorrow's Library by Jeffrey Licht
CS50
CS50 2014 - Week 9, continued
CS50
Essential Scale-Out Computing by James Cuff
CS50
iOS App Development with Swift by Dan Armendariz
CS50
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
3D Modeling and Manufacture by Ansel Duff
CS50
CS50 2014 - Week 5, continued
CS50
hello, world
CS50
CS50 2014 - Deep Thoughts - Hash Table
CS50
CS50 2014 - Deep Thoughts - Binary Tree
CS50
CS50 2014 - Deep Thoughts - Scratch
CS50
CS50 2014 - Deep Thoughts - MySQL
CS50
LaunchCode Visits CS50
CS50
CS50 Live, Episode 100
CS50
CS50 Field Trip to Google
CS50
This is CS50 AP
CS50
Week 4: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
Week 11: Monday - CS50 2011 - Harvard University
CS50
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
Week 12: Monday - CS50 2011 - Harvard University
CS50
Week 1: Friday - CS50 2011 - Harvard University
CS50
Week 3: Monday - CS50 2011 - Harvard University
CS50
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
Week 2: Monday - CS50 2011 - Harvard University
CS50
Week 9: Monday - CS50 2011 - Harvard University
CS50
Week 7: Monday - CS50 2011 - Harvard University
CS50
Week 5: Monday - CS50 2011 - Harvard University
CS50
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Monday - CS50 2011 - Harvard University
CS50
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
Week 10: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2010 - Harvard University
CS50
Related Reads
📰
📰
📰
📰
Breaking the Abstraction Tax: Mastering Custom C++ Operations for High-Performance Edge AI on Android
Dev.to · Programming Central
Five Habits I'm Unlearning After Claude Code 101
Medium · Data Science
Building a Telegram Math Bot with Native LaTeX and Guest Mode
Medium · AI
BugDetectAI is built for developers who want one place to analyze code, detect bugs, understand issues, and improve software faster.
Dev.to AI
🎓
Tutor Explanation
DeepCamp AI