Ganchimeg
Ganchimeg

Reputation: 59

how to redeclare a variable in different datatypes in c

How can i redeclared a variable in c. I know this can not be declared directly as follows;

int k = 5;
float k = 12.5;

Is there any possible way to do like this?

Upvotes: 1

Views: 1120

Answers (2)

chqrlie
chqrlie

Reputation: 144989

Dynamic typing is not supported in C as posted...

Yet there is a perverse way using the preprocessor (what else?) to make your code compile:

#include <stdio.h>

#define xglue(a,b) a##b
#define glue(a,b) xglue(a,b)
#define k glue(k_, __LINE__)

int main() {
    int k = 5;      printf("k = %d\n", k);  // this really defines and uses k_8
    float k = 12.5; printf("k = %g\n", k);  // this really defines and uses k_9
    return 0;
}

Output:

k = 5
k = 12.5

More seriously, you can redefine an identifier with the same or a different type, but only in a different scope, as explained in sidcoder's answer.

Here is an explanation for the preprocessor trick:

  • #define k glue(k_, __LINE__) defines the preprocessor symbol k to as a new symbol formed by concatenating k_ and the value of __LINE__, a preprocessor built-in symbol expanded to the source line number during preprocessing.
  • The glue macro must be defined as above because of arcane intricacies of the preprocessing specification well beyond the scope of the question.
  • the effect of this definition is every occurrence of k after the definition is replaced with k_xxx where xxx is the line number of the occurrence.

The main() function looks like this after preprocessing:

int main() {
    int k_8 = 5;      printf("k = %d\n", k_8);
    float k_9 = 12.5; printf("k = %g\n", k_9);
    return 0;
}

The definitions actually define variables with different names, as long as they appear on different lines. To use these variables, you cannot write k beyond the line where they are defined, so this trick is of limited use indeed.

Upvotes: 1

sidcoder
sidcoder

Reputation: 460

No, you cannot redefine a variable with different types within the same scope.

Although, there is one possible alternative. The same variable name can be used in a new scope or a subroutine. See the example below:

#include <stdio.h>

// Subroutine
void testing()
{
   int k = 9;
   printf("k = %i\n", k);
}

// Main Routine
int main() {
    int k = 5;
        
    // New scope
    {
       printf("k = %i\n", k);
       float k = 12.5;
       printf("k = %5.2f\n", k);
       testing();
    }
   
    return 0;
}

The output is:

k = 5
k = 12.50
k = 9

Upvotes: 4

Related Questions