0
0
Cprogramming~30 mins

Lifetime and scope comparison - Mini Project: Build & Apply

Choose your learning style9 modes available
Lifetime and Scope Comparison in C
📖 Scenario: Imagine you are organizing a small event and need to keep track of the number of guests in different rooms. You want to understand how variables behave inside and outside functions in C.
🎯 Goal: You will create a simple C program to compare the lifetime and scope of variables declared globally, locally inside a function, and as static inside a function.
📋 What You'll Learn
Create a global variable called guest_count initialized to 10
Create a function called update_guest_count that declares a local variable guest_count initialized to 5
Inside update_guest_count, declare a static variable static_guest_count initialized to 0 and increment it by 1 each time the function is called
Print the values of the global guest_count, local guest_count, and static_guest_count inside the function
Call update_guest_count three times from main and print the global guest_count after each call
💡 Why This Matters
🌍 Real World
Understanding variable lifetime and scope helps in managing data correctly in programs, avoiding bugs related to unexpected variable changes.
💼 Career
Many programming jobs require knowledge of how variables behave in memory and across function calls, especially in systems programming and embedded development.
Progress0 / 4 steps
1
Create the global variable
Create a global integer variable called guest_count and set it to 10.
C
Need a hint?

Global variables are declared outside any function.

2
Create the update_guest_count function
Create a function called update_guest_count that declares a local integer variable guest_count set to 5. Inside the function, declare a static integer variable static_guest_count initialized to 0. Increment static_guest_count by 1 each time the function is called.
C
Need a hint?

Static variables keep their value between function calls.

3
Print variable values inside update_guest_count
Inside the update_guest_count function, add printf statements to print the values of the global guest_count (print this before declaring the local variable), the local guest_count, and the static_guest_count.
C
Need a hint?

Use printf to show values. To access and print the global guest_count, place its printf before declaring the local guest_count to avoid shadowing.

4
Call update_guest_count and print global guest_count in main
Create a main function that calls update_guest_count three times. After each call, print the global guest_count using printf.
C
Need a hint?

Remember to include return 0; in main.