C

22K

Solutions

20

Articles & Videos

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.

Share tech news, updates, or what's on your mind.

Sign up to Post

Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and information against these types of occurrences.
0
Independent Software Vendors: We Want Your Opinion
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so many programmers use void as the return type. People, I'm sorry to tell you but that's just plain wrong!

The C/C++ standards are very (VERY) clear about the prototype for the main function. It can be one of the following two (and only the following two) formats:
 
int main(void) { /*...*/ }

Open in new window

and
 
int main(int argc, char *argv[]) { /*...*/ }

Open in new window


Any other prototype is ill-defined and will result in undefined behaviour. Don't be fooled into thinking that it must be okay to have void as the return type because, if it wasn't the compiler would chuck an error. Actually, the C / C++ standard does not require the compiler to do this. All the standard states regarding this matter is:

"If the main function executes a return that specifies no value, the termination status returned to the host environment is undefined."
Now, the chances are that you'll never see the effect of your mistake directly. By the time the brown stuff hits the fan, your program has likely ended. No, it won't be you who gets caught out, it'll be the user of your program who suffers at your hands.

You see, all processes return an exit code, that just happens to be …
4
 
LVL 58

Expert Comment

by:tigermatt
Comment Utility
A nice article and clearly a bug bear issue in software which exhibits these traits. Thanks. If the programmer did not see fit to define a sound interface with their program through attention to detail over return values, I would assume quality issues abound with the rest of the software, and would not hesitate to assume compiling it could result in a program which deletes all my data. [Through programmer incompetence or compiler-writer foolhardiness. They are invoking undefined behaviour, after all. :-)]

Some questions / remarks:

Common case behaviour

In reality, despite the standards, how do compilers behave in the common case? If I wanted to see the effects of this for myself, in code I compile, how would I do so?

I suspect the common case is that a (sane) compiler assumes what the programmer intended and synthesises a return of 0? This is certainly the behaviour I experience with gcc on a generic GNU/Linux x86 box. For example, the below:
#include <iostream>

using namespace std;

int main(void)
{
        int x = 3+4 * 5;
        cout << x << endl;
}

Open in new window

compiles down to:
000000000040082d <main>:
  40082d:       55                      push   %rbp
  40082e:       48 89 e5                mov    %rsp,%rbp
  400831:       48 83 ec 10             sub    $0x10,%rsp
  400835:       c7 45 fc 17 00 00 00    movl   $0x17,-0x4(%rbp)
  40083c:       8b 45 fc                mov    -0x4(%rbp),%eax
  40083f:       89 c6                   mov    %eax,%esi
  400841:       bf 80 10 60 00          mov    $0x601080,%edi
  400846:       e8 75 fe ff ff          callq  4006c0 <_ZNSolsEi@plt>
  40084b:       be 30 07 40 00          mov    $0x400730,%esi
  400850:       48 89 c7                mov    %rax,%rdi
  400853:       e8 c8 fe ff ff          callq  400720 <_ZNSolsEPFRSoS_E@plt>
  400858:       b8 00 00 00 00          mov    $0x0,%eax
  40085d:       c9                      leaveq 
  40085e:       c3                      retq   

Open in new window

In particular, the compiler in this case seems to have synthesised an explicit mov of constant value zero to EAX before the return, presumably by assumption that this is what I intended when flowing off the end without an explicit return statement.

I appreciate the GNU Compiler Collection is a behemoth, so what do I need to do to actually observe random values returned from the accumulator register? Use some other simplistic / esoteric compiler, perhaps a very simple one which receives little attention and generates code for some relatively obscure architecture? Something else?

To be clear, I am not advocating a wilful disregard for the standard; quite the contrary. However, I often find constructive examples can be useful in motivating a change in programmer behaviour, rather than arguments from standards (which often seem to fall on deaf ears or false arguments of "it doesn't affect me" or "my compiler is better than that").

Compiler warnings

Should the compiler warn me if there exists a path in the flow graph of a function returning a non-void type which fails to explicitly call return before the end of the function? Should it do this for the main method? Details of specific compilers are well outside the scope of the article, but I note in gcc's man page, the return-type warning explicitly excludes warning about the main method. Why should this be the case?

For C++, a function without return type always produces a diagnostic message, even when -Wno-return-type is specified.  The only exceptions are main and functions defined in system headers.

Infinite loops

What are the correct semantics here? Do I need to / should I be forced to include a return value? What about if I do this outside main(), where switching on return-type warnings throws an error about a missing return statement which would otherwise never be reached? (Assuming C++)
int main(void)
{
        while (true)
        {
                // do something
        }
}

Open in new window


Other functions

The following compiles but I presume it would be unwise to assume that anything will be well-defined after the call to foo() in main() which excludes a return statement?
int foo(int x, int y)
{
        /* something happens here */
}

int main(void)
{
        int bar = foo(3, 4);
}

Open in new window


These questions / remarks are not intended as a criticism of the article, so please don't misconstrue them as such! There are a fair few nuances in such a seemingly simple topic which are worth further exploration.

So, thoughts?
0
 
LVL 40

Author Comment

by:evilrix
Comment Utility
>> In reality, despite the standards, how do compilers behave in the common case

It's really hard to say because it depends on both the compiler and the optimization level to which the code has been compiled. Generally, compilers use the accumulator to return values so whatever was last placed in that register is what will be used. There are no guarantees to this; however, and the only sane (and correct) answer I can give you is that the behaviour is undefined.

>> compiles down to:
Remember, it depends what optimization level you built with. The outcome in terms of assembly code can be very different depending on whether you built optimised for speed or performance and to what level you optimise to.

>> seems to have synthesised an explicit mov of constant value zero to EAX before the return
If this is C++ then, yes, it will.

"Interestingly, whilst the main function MUST be defined to return an int, in C++ you don't have to actually return anything from main. The main function is treated as a special case; whereas, if you omit a return value the C++ runtime will automatically return zero for you."

I can't say for sure, but I have a feeling the C++ standards council made this change to account for the fact people were declaring main to return void. If you were to do the same here you would probably still see zero returned due to the fact the accumulator is being zero'd out; howver, in truth the behaviour is undefined - always was and alway will be (at least until the standards council say otherwise).

>> so what do I need to do to actually observe random values returned from the accumulator register?
Change there return type to void and compile as C not C++ code.

Or, you could try this...

#include <ctime>
#include <cstdlib>

int foo()
{
   return rand();
}

int bar()
{
   // look ma' no return value!
}

int main()
{
   srand((unsigned)time(0));
   
   foo();
   
   return bar(); // should return the return value of foo() (random)
}

Open in new window



>> Should the compiler warn me if there exists a path in the flow graph of a function returning a non-void type which fails to explicitly call return before the end of the function?
Interestingly enough this is not considered an error to not return a value from a function, it is considered to be undefined behaviour. This means the compiler does not have to generate an error but it will probably generate a warning (as long as warning levels are high enough). I suspect the reason is because it is possible to embed assembly into C/C++ code and so the function stack may be modified by the programmer outside the semantics of the C/C++ compiler's remit.

>> I note in gcc's man page, the return-type warning explicitly excludes warning about the main method. Why should this be the case?
Almost certainly because you can embed assembly into manipulate the function's stack-frame, which might be used to generate perfectly valid code but which the C/C++ compiler cannot validate and so will generate a warning.

>> Infinite loops - What are the correct semantics here? Do I need to / should I be forced to include a return value?
The compiler doesn't care - for the sake of sane program exit, maybe :)

>> where switching on return-type warnings throws an error about a missing return statement which would otherwise never be reached?
Well, that's a completely different problem - one of inaccessable control paths. Again, the standard does not mandate any warning be given for this and so that is compiler specific.

Other functions - The following compiles but I presume it would be unwise to assume that anything will be well-defined after the call to foo() in main() which excludes a return statement?
It's probably more correct to say the result is platform specific rather than undefined because it's really down to how the compiler works and it may be that this is actually intended (see my previous observation about embeding assembly). This code is not erroneous, it's just going to behave in a way that is arbitrary unless the programmer really knows what's going on at the assembly level and is controling it in some way.

>> These questions / remarks are not intended as a criticism of the article, so please don't misconstrue them as such!
All interesting points that makes me feel a separate article might be worth writing to cover in more detail the nuances of why there are somethings that would seem completely erroneous that the compiler will let you do and why somethings are undefined and some are unspecified (and what the difference is).

Matt, I hope my comments, above, help.
0
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode? They will have you believe that Unicode requires you to use a WCHAR (wide) character type and that Unicode cannot be represented by a CHAR (narrow) character type. In fact, both of these statements are completely and utterly false. Microsoft has misled you in the most egregious way.

Before we go any further, I need to clarify some terminology that is often confused. This is especially true of Windows programmers who, quite often, mistakeningly believe that using a wide character type means they are using Unicode:

Character Set: This is a complete set of characters recognized by the computer hardware and software.

Character Encoding: This is a way of encoding a character set, generally to fit within the boundaries of a particular data type. ASCII, ANSI and UTFx are all examples of character encodings.

Character Type: This is a fundamental data type used to represent a character.

These three things are intrinsically related. The character type chosen to represent a character set will have a direct impact on the character encoding used. In C++, the normal fundamental character types are either wchar_t (wide) or char (narrow). The size of the narrow and wide types are platform dependent, although C++11 has introduced fixed sized
7
 
LVL 32

Expert Comment

by:DrDamnit
Comment Utility
"When Microsoft gets involved."

You had me at the title.

Excellent work, sir.
0
 
LVL 29

Expert Comment

by:pepr
Comment Utility
+1 ... not because it helped myself [learned via more painful way], but because the articles like that should be spread to enhance the future. It the past, it was a lot of discussion about UTF-8 being impractical "because you cannot seek to the position". Actually, languages like Python 3 show, that beginners need not to care about how it is implemented inside. A unicode character is represented by a number (as one logical unit). If the programming language gives you tool for accessing the parts of the string easily you do not want to care about how many details must be solved. You simply enjoy when it works (and you feel safe when you know it is not an ad-hoc solution with some dark corners).
0
Summary:
This tutorial covers some basics of pointer, pointer arithmetic and function pointer.

What is a pointer:
A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of function.

How to Decide? 
int x;
Requirement is :  I would like to store address of x in another variable. How to do it?

My approach would be, which type of variable is it?
Here it's int. So I can consider int*.
int* p = &x; // p is a pointer to an integer
If we want to store address of char variable, then we'd consider char*.
If we want to store address of float variabe, then we'd consider float*.
Likewise if you want to store addess of a variable of type myStruct then you have to use myStruct*
Example:
     struct myStruct {
               int x;
               float y;
               char z;
     };
     struct myStruct StructVar; // myStructObj is a variable of type myStruct 
     // I want to store address of variable StructVar.
struct myStruct* p = & StructVar; // p is a pointer to a variable of type myStruct i.e StructVar here

Open in new window


Requirement is : I am having 5 integers, I want to store address of all integers in a single variable.
Soln: 
Consider array of 5 integer pointers.
Example:
      int a=1, b=2, c=3, d=4, e=5;
      int* p[5] = {&a, &b, &c, &d, &e}; // Here p is an array of 5 integer pointers.
      // Print all the elements.
      int i;
      for( i = 0; i < 5; ++i) {
         printf("%d ", *p[i]);
}

Open in new window

Requirement: I want to store address of function Fun in a variable.
void Fun(); // prototype of function Fun

How to achieve it?
What is Fun?- Fun is a function.
I want to store address of this fuction Fun.
So I have to consider pointer though I am storing address.
Which type of pointer? Is it int/char/float? No... No... No...
Then what?- Though I'm not going to store address of int/char/float in a variable, I can't use int/char/float pointer. Rather I am going to store address of function, So I have to use function pointer.

How to define?
1
 
LVL 9

Author Comment

by:Subrat (C++ windows/Linux)
Comment Utility
Yes things are correct.
Thanks.
0
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net.

This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn how to find the user's country code and country name, along with a numerical longitude and latitude.

Prior to doing this, add the CoreLocation framework. Make sure to import this framework as well.

#import <CoreLocation/CoreLocation.h>

Open in new window


Firstly, let's get into how to find the user's country code. Country codes can be US, CA, MX, UK, etc. The code to do this is very simple and is only 2 lines long, and it is as follows:

NSLocale *locale = [NSLocale currentLocale];
	NSString *countryCodes = [locale objectForKey:NSLocaleCountryCode];

Open in new window


Firstly, we create an NSLocale named Locale and we set the locale to the currentLocale. This means that we find the user's current local location. NSLocale is also used in automated localizing for the iPhone SDK. We then create an NSString called CountryCodes. This NSString is auto-released so we have to use it quickly. If you would like to have an allocated and retained NSString, you will have to assign the retain and nonatomic properties and also synthesize the string. If we add an NSLog statement, we can find the user's country code based on the NSLocale. We can set this up as follows:

NSLocale *locale = [NSLocale currentLocale];
	NSString *countryCodes = [locale objectForKey:NSLocaleCountryCode];
        NSLog(@"%@",countryCodes);

Open in new window


Now, to find the country name using NSLocale, we can add this line of code after the NSString *countryCodes is created:

NSString *countryName = [locale displayNameForKey:NSLocaleCountryCode value:countryCodes];

Open in new window

2

Preface

I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small and trivial, when few standard GUI controls could be arranged easily on the basic view and, then, connected to my code objects in Interface Builder.

At some point, though, the programs became a little bigger than a simple tutorial program, a little more complicated than one full-screen view with three labels and one button. Now I have to worry about having enough memory for my application and I so I now desire to eliminate everything related to Interface Builder.

This article shows how to accomplish this using an easy and fast trick.

iPhone Application Project.

Let's make a simple iPhone project:

1. Create new iPhone window-based application project.


In Xcode, in menu File, select "New Project...". In the project wizard sidebar select Application in the iPhone OS section. Select Windows-based Application in the right panel and click on Choose button in the bottom-right corner. In the Save panel give a name for the project. For example, "Simple", and click Save button.

These two screenshots illustrate this step: Xcode Project Wizard Set Project Name

2. Delete Classes folder and xib-file.


In Xcode project window, find Classes folder and delete it - select "Classes" item, click on the right mouse button and in the popup menu select "Delete". In the alert window click on "Also move to trash"
2
Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how:

~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
Important pre-programming comments:

I’ve never tried other options, only those recommended by Apple:

 1. Intel-based Mac computer running Snow Leopard
 2. iPhone SDK 3.2 installed on this computer

Also, this article discusses only how to create and simulate a simple iPhone app,
it does not get into the details of how to load and test on an actual iPhone.
~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

The iPhone Software Development Kit (SDK) can be downloaded for free from the Apple developer portall. You need to register yourself, but it is free. The installation is simple - agree with everything proposed by the installation wizard. When the installation is done, you can delete the installation package from your desktop.

Once you have the SDK, we can start.

ToDo

 1. Launch Xcode.
The Xcode application, by default, is installed into “/Developer/Applications” folder. You can find it in Finder and move the application to your Doc for faster access in the future.

 2. Create a new iPhone Window-based application.
In the File menu of Xcode select “New Project...” item. In the new project wizard choose iPhone OS in
6
 
LVL 33

Author Comment

by:pgnatyuk
Comment Utility
What do you mean?
In case you need a help please ask in the Objective-C Zone.
0
 

Expert Comment

by:Graeper
Comment Utility
I thought I was in the Objective-C Zone.  In Section 5. of your illustration above, you say "Find MainWindow.xib file in the “Group & Files” panel. It is in the Resources folder. Click on it to open Interface Builder. On the left side you see the Library window. It contains all Cocoa Touch controls. There is a search field in the bottom of this window. Type “push” there to find the Push Button in the Library. Drag this control to the prototype window - an empty window in the middle of your screen now, the window has title “First”."

I did everything you said but i couldn't find a Cocoa Touch Control labeled "push"
0
An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Outlet.  

The normal way to use an Outlet is:  In the 64-bit Xcode, you just add a property with the IBOutlet keyword, synthesize it, and set new text via that property, as follows:

In the interface section you declare a new property:
@property (retain) IBOutlet NSTextField * text;
In the implementation section you synthesize it; that is, have the compiler generate the get/set handlers:
@synthesize text;
If you want to set text to the control, just assign the property a value:
text.stringValue = @"Hello, World!";
To get data from the control, just access the property:
NSString* str = text.stringValue;

The same can be done without manual coding.  Doing it via the IDE is sometimes necessary, and it is useful and interesting to know how to do this.  

Example 1 -- Bind a text input to a label

Let's make a testing application:

1. Create new Mac OS X Cocoa project in Xcode

New Project wizard in Xcode. Choose Mac OS X, Cocoa application template
Set the project name and save it.I named the project as TextNoOutlet (shown on the screenshots above).

2. Add a string property

In the application delegate class I have added a string:
Application Delegate Class files in the projectInitially, the application delegate class is declared (in the TextNoOutletAppDelegate.h file) as:
#import <Cocoa/Cocoa.h>

@interface TextNoOutletAppDelegate : NSObject {
    NSWindow *window;
}

@property (assign) IBOutlet NSWindow *window;

@end

Open in new window

Replace that code with:
#import <Cocoa/Cocoa.h>

@interface TextNoOutletAppDelegate : NSObject
// Few lines removed from this place
@property (assign) IBOutlet NSWindow *window;

// New property added here
@property (copy) NSString *text;

@end

Open in new window

Press Control-S to save the header file.  Press Alt-Cmd-Up to switch to the m-file.  Synthesize the property:

Open in new window

2

C

22K

Solutions

20

Articles & Videos

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.