DATA Step, Macro, Functions and more

Length of variable

Frequent Contributor
Posts: 81

Length of variable

In the DATA step below, what is the length of the new variable, Type?

data orion.newloan; 
   set orion.records; 
   if Code='1' then Type='Fixed'; 
   else Type='Variable'; 
   length Type $ 10; 


 a.  5
 b.  8
 c.  10
 d.  It depends on the first value of Type in orion.records.



What is its answer and how ??  i think D is the correct answer.Please tell me 

Super User
Super User
Posts: 9,599

Re: Length of variable

Is there a variable called type in: 

   set orion.records; 

?  If so it will inherit the length from that dataset.  If it does not exist in that dataset then the SAS program will take the first time it encounters the variable, and set the length to the value assigned to it at that point which in this case is: 


Which is 5 characters in length.  Thus in this example the answer is either:
- the length as assigned to the existing variable in orion.newloan


- a) 5, as that is the first appearance of type in the statements

Super User
Posts: 10,217

Re: Length of variable

It can't be D because the length is set while the data step is compiled, but the first value is available only when the data step already runs.


Run the step, and look at the log, as it will give you a BIG clue about what happens while the data step is compiled-

Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Valued Guide
Posts: 590

Re: Length of variable

Since the question says "new variable" that means it is not present in the input dataset. Since the length statement is mentioned after its length is already defined (TYPE="Fixed" length=5). For new variables if the length is not defined before then it will take the datatype from the first value ie "Fixed" and remaining values will be truncated to length 5.


In the log you can see a warning:

WARNING: Length of character variable Type has already been set.
Use the LENGTH statement as the very first statement in the DATA STEP to declare the length of a character variable.

Ask a Question
Discussion stats
  • 3 replies
  • 1 like
  • 4 in conversation