Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a length limit on g++ variable names?

Tags:

See title​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

like image 503
anon Avatar asked Apr 21 '10 10:04

anon


People also ask

What is the maximum length of a variable name?

Variable names can be upto 32 digits.

Can variables have unlimited length?

Explanation: Variable names can be of any length.

Does the length of a variable name matter?

It doesn't matter.

How long can variable names be in C++?

Variable names in C++ can range from 1 to 255 characters. All variable names must begin with a letter of the alphabet or an underscore(_).


2 Answers

Short Answer:

No

Long Answer:

Yes, it has to be small enough that it will fit in memory, but otherwise no, not really. If there is a builtin limit (I don't believe there is) it is so huge you'd be really hard-pressed to reach it.

Actually, you got me really curious, so I created the following Python program to generate code:

#! /usr/bin/env python2.6
import sys;
cppcode="""
#include <iostream>
#include <cstdlib>

int main(int argc, char* argv[])
{
     int %s = 0;
     return 0;
}
"""

def longvarname(n):
    str="x";
    for i in xrange(n):
        str = str+"0";
    return str;

def printcpp(n):
    print cppcode % longvarname(n);

if __name__=="__main__":
    if len(sys.argv)==2:
        printcpp(int(sys.argv[1]));

This generates C++ code using the desired length variable name. Using the following:

./gencpp.py 1048576 > main.cpp
g++ main.cpp -o main

The above gives me no problems (the variable name is roughly 1MB in length). I tried for a gigabyte, but I'm not being so smart with the string construction, and so I decided to abort when gencpp.py took too long.

Anyway, I very much doubt that gcc pre-allocates 1MB for variable names. It is purely bounded by memory.

like image 102
Michael Aaron Safyan Avatar answered Sep 21 '22 17:09

Michael Aaron Safyan


an additional gotcha, some linkers have a limit on the length of the mangled name. this tends to be an issue with template and nested classes more than identifier length but either could trigger a problem afaik

like image 25
jk. Avatar answered Sep 23 '22 17:09

jk.