1

I don't know what the technical term is but I would like to do following:

int var_a;
int var_b;
int var_c;
char letter;

letter = 'b';
printf("%d", var_'letter');

However, I don't want to use if statements. Can I directly sub in the rest of the variable name with the variable char so that the computer would see "var_b"?

3
  • 4
    No, you cannot do this. Commented Jan 31, 2016 at 23:30
  • 2
    A term for this is 'dynamic variable name', which C does not support. Commented Jan 31, 2016 at 23:34
  • hmm, thanks, the exact term I was looking for Commented Jan 31, 2016 at 23:38

1 Answer 1

6

Not possible. You could try using an array and indexing it like this:

vars[letter - 'a'];

Where vars[0] would correspond to your var_a and so on.

Sign up to request clarification or add additional context in comments.

2 Comments

I was going to post something similar. It might be better to declare an enum to use for the index rather than using character literals. E.g., enum my_vars { A, B, C }; vars[A];
thanks, i was hoping dynamic vars were allowed in C, guess not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.