Vikram Baichbal
last year
Vikramcountry asked

Do we need to redeclare a variable when changing its value? For example, should we use the "int" declaration again to change the value of "age" variable and print it?

Abhay Jajodia
Expert
last year
Abhay Jajodia answered

Hi there! That's a great and very common question when starting to learn about variables in C programming.

To answer your question: You do not need to use int again to change the age variable and print it.

The int keyword is only used when you first declare a variable to specify that the variable is of type integer. Once you've declared the variable, you can change its value without redeclaring its type.

In your example:

#include 

int main() {

    // Create an int variable and print it 
    int age = 25; // Declare and initialize the variable
    printf("%d ", age);

    // Assign a new value and print it
    age = 31; // Change the value of the already declared variable
    printf("%d", age);

    return 0;
}

Initially, you declare int age = 25; to create an integer variable age and set its value to 25. After that, you can simply change the value using age = 31; without using int again. The printf function can then print the updated value without any further declarations.

Hope this helps! Feel free to ask if you have any more questions. 😊

C
This question was asked as part of the Learn C Programming course.