1. Scopes and Durations of variables: A variable is defined by declaring it in t
ID: 3764874 • Letter: 1
Question
1. Scopes and Durations of variables: A variable is defined by declaring it in the program. Thus, for example, in function f(int i), i is declared as a variable. When a variable is declared storage is allocated for the variable. Same name can be used to define different variables in the same program. Different storage is allocated for each variable. Because of using the same name for different variables in the program, it requires rules for conflict resolution in using the variables. This has been discussed in the class. Following is a part of a program declaring three variables (line 1, line 2 and line 8) with the same name i. (a) Give the scopes of these three variables. Scope can be defined as within the entire file, within the entire function, within the entire block or part of a block. Scope of declaration of line 1: Entire file. Scope of declaration of line 2: Entire function f Scope of declaration of line 8: Staring from the declaration up to the end of that block. (b) Give the print-out of the printf() functions. #include Int i=1; Void f(int i) { Printf(“i1= %d ”, i); I=2; Inf (i>1){ Printf(“i2= %d ”, i); Int i; Printf(“i3= %d ”, i); I=3; } Printf(“i4= %d ”, i); I=4; } Int h(void) { Printf(“i5=%d ”, i); } Int main(){ F(6); H(); } (c) Values of the variables inside a function are not retained when the function returns. What is the mechanism for retaining the value in a variable even after the function returns. Define the variables as static.
Explanation / Answer
b)
Sample code:
Sample output:
Code to copy:
// scopeofVariables.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<stdio.h>
using namespace std;
static int i=1;//the scope of this variable is through out the file
void f(static int i) //the scope of this varible is with in the function
{
printf("i1= %d ", i);
i=2; //re initialize the varible i;
if(i>1)
printf("i2= %d ",i);
int i; i=3; //the scope of this varible is with in the if block
printf("i3= %d ", i);
}
printf("i4= %d ", i); //the i values is taken from global varible i=1
i=4;
}
int h(void) //the scope of this varible is with in the function
{
printf("i5=%d ", i);
return 0;
}
int main()
{
f(6); //the scope of this varible is with in the function
h();
system("pause");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.