Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of typedefs

Tags:

c

I am not at a computer so cannot test this at the moment but have some code to review. I'm still somewhat in a C++ mindframe unfortunatley.

So, when a typedef is declared within a C source file what is its scope? I am aware that to make functions and variables only available within the same translation unit you need to make them static and I was wondering if this is the same for typedefs?

like image 735
Firedragon Avatar asked Apr 25 '12 08:04

Firedragon


People also ask

How do Typedefs work in C++?

typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.

Why is typedef is used in structure?

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.

Should I use typedef C++?

The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.

What is difference between typedef and #define?

typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc. typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.


2 Answers

Here is an example showing typedef and scope:

typedef int foo_t;

foo_t x = 1;

double bar(double x) {
    typedef double foo_t;
    foo_t y = 2.0;
    return y + 3.14156;
}

foo_t z = 1;
like image 164
MattW Avatar answered Sep 19 '22 16:09

MattW


Typedefs are declarations. If you have a typedef in a C file, no other C file will be aware of that since they are compiled indepedendly of each other.

For a typedef in a header, it will of course be visible from all C files that include it.

like image 28
unwind Avatar answered Sep 18 '22 16:09

unwind