知识点2:变量和作用域(variables and scope)

As you start working with functions, another thing is going to become really important to understand, which is the concept of variable scope.

There are two primary scopes in C, local variables and global variables.

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, on the 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.


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 callee, 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, 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 side effect of that?

That means that the variable in the caller, the function that is making the function call, is unchanged unless you override it.

for example:

int main(void) {
    int foo = 4; 
    foo = triple(foo);
}

int triple(int x) {
    return x *= 3
}

In this code foo is not changed at all.

Int foo equals 4, call triple of foo, inside of triple, we would expect that foo would be multiplied by 3 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 int foo equals 4, foo equals triple foo, when we make that call, triple gets its own copy of foo, its own copy of 4.

It says return 4 times 3, 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 variable. So now if we add another line of code here
at the end of main to print out the value of foo, it would in fact print out 12.

But when variables have the same name, scope issues can get a little trickier to parse.

for example:

int increment(int x);

int main(void) {
    int x(red or m)  = 1;
    int y;
    y = increment(x(red or m));
    printf("x is %i, y is %i\n", x(red or m), y);
}

int increment(int x(blue or i)) {
    x(blue or i)++;
    return x(blue or i);
}

do you know what would 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 in main, the last of which is a print statement. And remember, 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's declaration at the top there. It was kind of a distraction. It's not its own variable. It 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 main red. And I've colored every instance of x that's local to increment blue.

Notice in that third line of main, y equals increment x, that increment is not being passed main'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 main 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 main, and x sub i, or the blue variables in the previous slide, are the instances of x that are local to increment.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容